0

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).

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
SKSKSKSK
  • 545
  • 1
  • 4
  • 15
  • 1
    Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Carlos Horn Dec 04 '22 at 10:28

2 Answers2

0

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

Try to use next syntaxis

import ...directory_3.file_2

Ryabchenko Alexander
  • 10,057
  • 7
  • 56
  • 88
0

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

SKSKSKSK
  • 545
  • 1
  • 4
  • 15