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