I’m using vs code.
I’m running file1.py, it imports a function from file2.py.
The file structure is as follows:
feeds
├── bulk_load
│ ├── __init__.py (empty)
│ └── file2.py
├── __init__.py (empty)
└── file1.py
in file1.py
the following works:
from bulk_load.file2 import func123
but the following doesn’t:
sys.path.append("bulk_load")
from file2 import func123
Error is
ModuleNotFoundError
No module named file2
I dont really understand why.
3
Answers
I have just recreated with the file structure
in file1.py:
in file2.py
and running
python file1.py
from feeds outputs:hello
so I am unable to recreate your error, sys.path.append works fine.
Can you print sys.path and see if that looks correct?
You’re importing it the wrong way. There’s no need to use something like
sys.path.append()
.bulk_load
dir is automatically considered as a module (Python 3.3+), so you should import right from it../bulk_load/file2.py
./file1.py
Run:
It is how entries in [Python.Docs]: sys.path are handled (absolute vs. relative).
I’ve searched [Python.Docs]: Modules – The Module Search Path (and a couple of other pages) but I didn’t find a way that clearly states it.
I prepared the following structure (I’ll be reusing this console):
code00.py:
mod00.py:
Output:
As seen, relative paths depend on the current location (CWD), so in order to make sure that your code works from every location, append the full path.
Of course there are alternatives, but I’m not going to insist on them.
For more details on this kind of errors (and ways to get past them) check: