There are 10+ SO posts about this already, none of the answers works for me and I still haven't seen an example of someone importing something from a sibling directory.
src
__init__.py
test.py
package1
__init__.py
module1.py
package2
__init__.py
module2.py
(_init_.py should not be necessary on python versions greater than 3.3 but I still have them there as they make no difference)
in test.py I have
import package1.module2
and it works fine however the problem is when I want to import something from package2 to package1, and vice versa. I have tried different import methods in module2.py and I receive these different error messages:
import src.package1.module1.py
with the error:
ModuleNotFoundError: No module named 'src'
and
from .. import package1
with the error:
ImportError: attempted relative import with no known parent package
The top answer here: How do I import a Python script from a sibling directory? also give me the exact error message as I showed above. The answers here: How to import a Python module from a sibling folder? changes nothing. Am I missing something or should it not be possible to import stuff between different folders/packages? Do I need the "sys.path hack"?
I gave almost all of the solutions given for similar questions a try, but none of them worked for me! However, after banging my head to the wall, I found out that this solution does work by just removing one dot:
import sys
sys.path.append('..')
Just remove one dot from string within append method, i.e.:
sys.path.append('.')
or your can use:
sys.path.insert(0, '.')
Then you can import any module from a sibling folder. I tried this using python 3.9.13 and it worked well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With