I'm attempting to include & call Python functions from a different py
file, by providing a relative file path to the os.path.join
function call.
Let's say I have two py
files, TEST1.py
and TEST2.py
, and a function defined inside of TEST2.py
called TEST3()
.
Alongside the following directory structure:
TEST1.py
|____________TEST2.py
So TEST1.py
is located one directory above TEST2.py
.
With the following code inside of TEST1.py
:
import os
CurrDirPath = os.path.dirname(__file__)
CurrFileName = os.path.join(CurrDirPath, "../TEST2.py")
import TEST2
if (__name__ == '__main__'):
print(TEST2.TEST3())
And the following code inside of TEST2.py
:
def TEST3():
return "test"
Results in the following exception upon attempting to run TEST1.py
:
import TEST2
ModuleNotFoundError: No module named 'TEST2'
What is the proper way to include Python functions from a relative file path?
Thanks for reading my post, any guidance is appreciated.
if your files arranged like this:
│ test1.py
│
└──── sub_folder
│ test2.py
Below Code should work:
import os
import sys
CurrDirPath = os.getcwd()
DesiredDirPath = CurrDirPath + os.sep + "sub_folder"
sys.path.insert(1, DesiredDirPath)
import TEST2
if (__name__ == '__main__'):
print(TEST2.TEST3())
But, if your files arranged like this:
│ test2.py
│
└──── sub_folder
│ test1.py
Below Code should work:
import os
import sys
CurrDirPath = os.getcwd()
# Below command, goes one folder back
DesiredDirPath = os.path.normpath(CurrDirPath + os.sep + os.pardir)
sys.path.insert(1, DesiredDirPath)
import TEST2
if (__name__ == '__main__'):
print(TEST2.TEST3())
first you need to get Desired working directory and Then you need to add this path to known paths of the system, clearly at runtime, by this code:
sys.path.insert(1, DesiredDirPath)
Now you can import TEST2
There is nice discussion at below link: Importing files from different folder