0

I want to import a function from a file inside a subfolder. The filename differs depending on the previous code, that's why i got the 'file' variable.

I have come up with different code for Windows and Linux.

The folder layout is like this:

#ls project/
file.py  subfolder
#ls project/subfolder/
subfile.py

file.py

import os
os.chdir('subfolder')
file = 'subfile'
if os.name == 'nt': #for windows
    exec('from ' + file + ' import *')
else:
    exec('from subfolder.' + file + ' import *')
print(subfunction())

subfile.py

def subfunction():
    return 1

This different behavior seems odd to me, since it is the same programming language on 2 different os. Does someone have a better code example than this or can elaborate why it is like it is?

Note: on windows i got python version 3.6.5 from Anaconda and on linux Python 3.7.4

ramden
  • 3
  • 1

1 Answers1

0

The correct way is just the Linux way. I'm not sure why the windows approach works for you.

os.chdir() should not affect the path where python looks for modules to import. The path where python looks for them is located in sys.path.

See sys.path and for further information read through BrenBarn's answer.