0

For example, if dir1 contains abc.py that imports config.py and dir2 also contains config.py, how do I import config.py from dir 2 into abc.py?

Here's a visual representation:

dir1/abc.py
     config.py
dir2/xyz.py
     config.py

I have tried this so far

import sys
sys.path.insert(0, '../dir2')
import config as lconfig 
print(sys.path)
print(dir(lconfig))

But it seems it imports the config.py from dir1 not from dir2

I confirmed by printing out sys.path.

also, print(dir(lconfig)) does return the path for dir2.

Kalangu
  • 135
  • 10
  • Instead of manipulating `sys.path` you should create a proper project structure with packages. – Klaus D. Jun 26 '19 at 00:36
  • 1
    More on package relative imports , [link](https://docs.python.org/3/reference/import.html#package-relative-imports) and [here](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – Saurabh P Bhandari Jun 26 '19 at 00:57

1 Answers1

1

If the parent of dir1 and dir2 is in the path, you can do this:

import dir1.config
import dir2.config
print('dir1/config is: %s' % dir1.config)
print('dir2/config is: %s' % dir2.config)

If you like, you can give them shorter but meaningful names:

import dir1.config as config1
import dir2.config as config2
John Gordon
  • 29,573
  • 7
  • 33
  • 58