1
votes

I have a python file named x.py which imports another file named y.py. y.py itself imports z.py, y.py and z.py are in the same directory but x.py is in the parent directory. When I use relative import in y.py e.g. import .z y does not work and x works. When I change import to import z y.py works but x.py does not work

dic1  
    |__x.py
    |__dic2
         |__y.py
         |__z.py

x imports y
y imports z

is there any solution to import a python file that imports another file in different directories.

2
Add an empty file named __init__.py in every folder and then try again - singrium

2 Answers

2
votes

Packages in Python need to have an __init__.py file at the root of them. Here I'm a bit confused as to what is a package and what is the root directory.

I would have something like this:

<root_directory>
  |__ setup.py
  |__ <other top level files>
  |__ dic1/
    |__ __init__.py
    |__ x.py
    |__ dic2/
      |__ y.py
      |__ z.py

You've tagged this as python, so I don't know if you're using Python2 or Python3. Given the former is end of life, you should really be using Python3.

You can import things relative to the root package, in this example, dic1.

If using python2, you need from __future__ import absolute_import at the top of every file.

x.py

from dic1.dic2 import y

y.py

from dic1.dic2 import z
0
votes

Thanks Blueteeth and Sofian for your responses. Apology for my incomplete question and I think I could not tell the exact point.

Finally, I used
import sys sys.path.insert(0, "dic2") in y.py