1

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"
2
  • Why would the relative import work if the full path doesnt work? Please explain. Commented Feb 15, 2018 at 23:08
  • with those two lines, can you please update your question with the full TraceBack // Error Commented Feb 16, 2018 at 8:58

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.