I currently have the following directory structure:
Folder/
package/
__init__.py, .. many python files
subfolder/
file1.py
Now, my problem is that I am in the Folder directory. I can run python and then run import package. This works fine. However, in my file1.py, I import package at the beginning but when I run python subfolder/file1.py, it cannot find module named package.
Edited: I currently have __ init__.py (with 2 underscores)
2 Answers 2
In the latter case, Python cannot find package because it is not visible on sys.path. sys.path will contain amongst other things the parent directory of the script currently being executed.
So when you run Python from Folder, this entry is /path/to/Folder and import package correctly finds the package directory from this. In your second case, this entry will be /path/to/Folder/subfolder and import package will fail because it tries to find /path/to/Folder/subfolder/package.
1 Comment
sys.path inside a script to bring the right packages into scope (i.e. by adding /path/to/Folder to sys.path in file1.py before importing package), but often a rethink of your architecture is a better approach.Rename _init_.py to __init__.py (two underscores)
_init_.pyto__init__.pyshould help you out