usustarr
usustarr

Reputation: 418

Import Python modules from a different folder

I have following directory structure,

/Scripts/myPyFile.py #myPyFile.py does impoarts from multiple other file(/Scripts/x.py, /Scripts/y.py so on) def modA() def ModB()

/Script/allScripts/main.py (I want main.py to be able to import modA from myPyFile.py)

I did google this issue and tried few methods, but I'm getting errors due to the fact that myPyFile.py imports other modules.

What is the best way without having to add this to the path variable? I'm on Win7 Python 3.4

I have tried the linked solution, but it doeesnt work for me.

sys.path.insert(0, r'C:\Users\Configuration\Script')
from myPyFile import getGatewayDevId   #This gives so many errors about myPyFile import. Same issue if I try "import myPyFile"

Upvotes: 1

Views: 290

Answers (1)

Edwin van Mierlo
Edwin van Mierlo

Reputation: 2488

In your question you detail that myPyFile.py is in directory /Scripts (please note the 's' at the end of 'Scripts')

Then you do:

sys.path.insert(0, r'C:\Users\Configuration\Script')

Seems that you are missing a trailing 's' on the directory name.


This is how I do it:

Structure on Disk:

C:\
 |
 test\
    |
    py1\
    | |
    | __init__.py 
    | file1.py
    |
    py2\
      |
      __init__.py
      file2.py

Both __init__.py files are empty

C:\test\py1\file1.py

# file1.py

def my_function1():
    print('{}.my_function1()'.format(__file__))

def my_function2():
    print('{}.my_function2()'.format(__file__))


def main():
    my_function1()
    my_function2()

if __name__ == '__main__':
    main()

now we are importing file1 into file2

C:\test\py2\file2.py

# file2.py

import sys
from pathlib import Path 

filepath = Path(__file__).resolve()
root_folder = filepath.parents[1]
sys.path.append(str(root_folder))

from py1 import file1 

file1.my_function1()
file1.my_function2()

running file2.py gives the following correct output:

C:\test\py1\file1.py.my_function1()
C:\test\py1\file1.py.my_function2()

if you like to know all parents (folders), you can always quickly check:

from pathlib import Path 

filepath = Path(__file__).resolve()
for i in range(len(filepath.parents)):
    print(i, filepath.parents[i])

Upvotes: 1

Related Questions