M.H Mighani
M.H Mighani

Reputation: 198

module not found error problem when trying to import from another folder

I have this folder structure:

--test
    first.py
    --numpad
          second.py
          third.py

in the first.py i have this line of code:

from numpad import second

and in the second.py file i have this:

import third

but in the test folder when i run

python first.py

i get this error message:

ModuleNotFoundError: No module named 'third'

note: i have also tried adding __init__.py to my numpad folder but it didnt work

Upvotes: 3

Views: 4227

Answers (2)

Arne
Arne

Reputation: 20147

Since the python interpreter is started within test, that's where it looks for imports. You can learn about pythons's search behavior for imports through the docs, if you're interested in the details.

To solve your problem, there are a bunch of ways to do it, the best one depending on how you plan to use your code. If you plan to write a library, it might make sense to package it, which would give you access to a global namespace that you can use.

But if you just want it to work right now, and only ever are going to run the interpreter from the same place (i.e. your test folder), defining the third file as a local one should do it:

second.py

from . import third

third.py

print('third here, not an import error')

This works for me:

~/test$ tree . 
.
├── first.py
└── numpad
    ├── second.py
    └── third.py
~/test$ python3.6 first.py
third here, not an import error

Upvotes: 2

MegaEmailman
MegaEmailman

Reputation: 545

I might be wrong on this, but I'm pretty sure you'd have to set up your environment variable to look in that specific folder. Which would be way more of a hassle than just adding your homemade modules to your default modules folder.

Upvotes: 0

Related Questions