Home > Software design >  how to import a module that using another module at the grandparent directories in Python
how to import a module that using another module at the grandparent directories in Python

Time:12-05

I'm trying to run a python file that imports a module using other modules in the grandparent folder. The file structure is:

directory_0
   |
   directory_1
   |   |
   |   directory_2
   |      |
   |      __init__.py (define the method A and import another method B from file_2.py)  
   |      |
   |      file_1.py
   |
   directory_3
      |
      file_2.py (define the method B)

I want to run file_1.py that imports method A defined in __init__.py, and __init__.py it imports method B from file_2.py. I'm currently at /directory_0/directory_1/directory_2 to run the command python file_1.py. It throws ModuleNotFoundError: No module named directory_3.file_2 How to make it run? and which path should I go to run this script (file_1.py).

CodePudding user response:

Probably you need __init__.py in all 1-3 directories.

Try to use next syntaxis

import ...directory_3.file_2

CodePudding user response:

my final approach is import in the way: in file_1.py:

from directory_1.directory_2 import A

and jump to the path that can access all children modules to run file_1.py as a module: from /directory_0 run by python -m directory_1.directory_2.file_1

  • Related