Let's say that I have the following files with given paths:
/home/project/folder1/common.py
/home/project/folder2/common.py
So, these files have the same name but they are in different folders.
And I need to import both of these files in the same python script that is located in a separate path, as following:
/home/project/folder3/abc.py
If it was only 1 file I needed to import, I could do the following:
import sys
sys.path.append(r'/home/project/folder1')
import common as c
And then I could access e.g. constants from /home/project/folder1/common.py as c.MY_CONSTANT.
But how can I import both /home/project/folder1/common.py and /home/project/folder1/common.py in the file /home/project/folder3/abc.py ?
Please note that constants that I would like to access from abc.py may have the same names. With other words, MY_CONSTANT may exist in both common.py files.
What I would like to achieve is the following (though I know that this is wrong syntax in Python):
import /home/project/folder1/common as c1
import /home/project/folder2/common as c2
... so that I can access both files with c1. and c2..
So, how can I import both files in the same Python script?
CodePudding user response:
It's a bit odd calling both files common.py, by their naming and placement they're anything but common :). But here you go. You need to make your abc.py script "see" your top-level project directory. Since it is in /home, adding the path to your home directory achieves that.
import sys
sys.path.append(r"/home")
from project.folder1 import common as c1
from project.folder2 import common as c2
