0

How can I import file from subdirectory of parent of parentdirectory? I know that this doesn't make sense so let me explain. I want to import the file test.py into the file example.py.

Here is the directory structure:

directory1 
+-- directory2
    +-- test.py
+-- directory3
    +-- directory4
        +-- example.py
Bando
  • 1,223
  • 1
  • 12
  • 31
Serket
  • 3,785
  • 3
  • 14
  • 45

4 Answers4

0

Just make sure folder also contains an __init__.py, this allows it to be included as a package

sitharthan
  • 104
  • 1
  • 1
  • 10
0

You have serveral options:

  1. Like the comment said you can use a full path: /home/User/directory1/directory2/test.py Map that file to a variable and use it. (Watch out with using python built in names like test)
  2. use os.chdir and change your dir to the root of you directory1 and call directory2/test.py
  3. make an init.py and use it as a package with the from [directory] import [module]
Sneil
  • 134
  • 2
  • 11
0

Add __init__.py file inside each directory, parent directory and subdirectories

parent/
    __init__.py
    package_1/
        __init__.py
    package_2/
        __init__.py
    package_3/
        __init__.py

from parent.package_1 import ....

If doesn't work, try to configure PYTHONPATH, in case of IDE like PyCharm, there's a flag (checkbox) in run/debug configuration

or you might add module to the default path using sys.path.insert(...)

import sys
sys.path.insert(0, module_full_path)

You could check path, using print(sys.path)

4.Pi.n
  • 1,151
  • 6
  • 15
0

Here you go =^..^=

from pathlib import Path
import sys

path = Path(__file__).parents
sys.path.append(str(path[2] / 'directory2'))
import test
Zaraki Kenpachi
  • 5,510
  • 2
  • 15
  • 38