I am new to Python. This really confused me!
My directory structure is like this:
Project
| - subpackage1
|- a.py
| - subpackage2
|- b.py
| - c.py
When I import a.py
into b.py
with from subpackage1 import a
, I get a ModuleNotFoundError. It seems like I cannot import a file from the parent directory.
Some solutions suggest to add an empty file __init__.py
in each directory, but that does not work. As a work around, I have put the following in each subfile (i.e., a.py
and b.py
) to access the parent directory:
import os
import sys
sys.path.append(os.path.abspath('..'))
I have tried to output sys.path
in subfiles, it only includes the current file path and anaconda path, so I have to append ..
to sys.path
.
How can I solve this problem? Is there a more efficient way?
b.py
insubpackage2
needs a parameter ina.py
, and then I should addsys.path.append(...)
at the head ofb.py
, and if I don't do that I should movea.py
orsubpackage1
insubpackage2
, right? – Engracia