Reputation: 2571
I've seen tips on how to import from a subfolder. The problem is importing from another folder in the same parent folder. The current structure is like this:
test
__init__.py
|-- folder1
|-- __init__.py
| |-- A.py
|-- folder2
| |-- __init__.py
| |-- B.py
A.py is:
hi = 1
print "hi", hi
B.py is:
from folder1 import A
print "imported"
When I do python B.py
, I get an error:
File "B.py", line 1, in <module>
from folder1 import A
ImportError: No module named folder1
How can I import A.py? Ideally, folder structure does not change.
Upvotes: 0
Views: 438
Reputation: 362458
The problem here is that folder1
and folder2
are subpackages, and the package is the parent directory i.e. test
.
Whatever path the parent directory of test
is will need to be in your sys.path
. You can do this, for example, with the PYTHONPATH
environment variable.
Then you should have, in module B.py
:
from test.folder1 import A
Upvotes: 1