pythonpython-3.xrelative-pathabsolute-pathsys.path

Import directory errors with Python 3.5 and above


I want to import modules from folder and subfolder with Python 3.6. Currently I have a structure like this.

└── project
    │   main.py
    ├── package1
    │   ├── __init__.py
    │   └── module1.py
    └── package2
        ├── __init__.py
        ├── module2.py

When I import module1 and module2, I have no problem with that.
Within main.py having this scripts to import both modules.

from package1 import module1
from package2 import module2

It works fine!

But I want to move package2 with module2 into a subfolder under package1 as shown below:

└── project
    │   main.py
    └── package1
        ├── __init__.py
        ├── module1.py
        └── subpackage1
            ├── __init__.py
            ├── module2.py

And want to call module2 from main.py. Having tried following path and scripts does not fix my problem I get import error, it can not find the path.

Within main.py having this scripts to import both modules.

from package1.subpackage1 import module2

or

from package1.subpackage1.module2 import Class_in_module2

or

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from package1.subpackage1 import module2

It does not work. Path can not be found! Any help appreciate!


Solution

  • Since the from keyword accepts an hierarchy of folders and import the specific method from the file, this should work.

    from MainFolder.SubFolder.SomeDotPy import foo,bar,somevalue