I am in the z.py
file, and I would like to import the x.py
file and also a function of it (function_example). Considering that I cannot use directly import folder1
or from folder1.x import *
,
how can I import file x? How can I enter the folder1 folder when I am in the z.py file of the other folder?
my_project/
engine/
folder1/
x.py
folder2/
y.py
other/
z.py
On the web I read that I could use this, but it doesn't work for me:
import sys
sys.path.insert(0, 'my_project/engine/folder1/x')
import x
from x import function_example
engine.folder1.x.function_example(sogg) #use function imported
CodePudding user response:
By default, you can't. Python just search within the same directory for the imported files and functions.
But, you can use the following code:
# some_file.py
import sys
# caution: path[0] is reserved for script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')
import file
Reference: This question in Stack Overflow
CodePudding user response:
In your case this would be:
import sys
sys.path.insert(1, '/my_project/engine/folder1')
import x
In your question, you have provided path to your x.py file. That does not work. Just have your path to your folder folder1. Now, you can use any function inside x.py file.