1

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.

Runsva
  • 365
  • 1
  • 7

2 Answers2

1

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

Abolfazl
  • 637
  • 4
  • 7
0

You can use importlib

If test2.py in located in subfolder, for example:

│   test1.py
│
└──── sub_folder
      │   test2.py

So for test1.py:

import os
import importlib.util
import sys


CurrDirPath = os.path.dirname(__file__)
CurrFileName = os.path.join(CurrDirPath, r"sub_folder\test2.py")

spec = importlib.util.spec_from_file_location("test2", CurrFileName)
test2 = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = test2
spec.loader.exec_module(test2)

if __name__ == '__main__':
    print(test2.test3())

In test2.py:

def test3():
    return 'test2'

More details in answer How can I import a module dynamically given the full path?