Import Python File In Another Directory Failed
Solution 1:
Have to create __init__.py
file inside the test dir:
Because The __init__.py
files are required to make Python treat the directories as containing packages.
parent/
child1/
__init__.py
file1.py
child2/
__init__.py
file2.py
From the error:
If run the child2/file2.py
file directly. You are not able to access child1/file1.py
from the child2/file2.py
Because only from the parent directory can access the child.
If have a folder structure like:
parent/
child1/
__init__.py
file1.py
child2/
__init__.py
file2.py
file3.py
If we run the file3.py
file. Can able to access both child1/file1.py
, child2/file2.py
in file3.py
Because It is running from the parent directory.
If we need to access child1/file1
from child2/file2.py
, We need to set the parent directory:
By running this below command we can achieve it...
PYTHONPATH=. python child2/file2.py
PYTHONPATH=.
It refers the parent path. Then runs child2/file2.py
file from the shell
Solution 2:
It's not a strange problem, imports simply don't work like that.
From the official documentation: https://docs.python.org/3/tutorial/modules.html
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default.
You could look into relative imports, here's a good source: https://stackoverflow.com/a/16985066/4886716
The relevant info from that post is that there's no good way to do it unless you add core
to PYTHONPATH
like Shawn. L says.
Solution 3:
When I tried your case, I got
Traceback (most recent call last):
File "file2.py", line 3, in <module>
from core import file1
ImportError: No module named core
The reason is that Python
does not find core
. In this case, you need to add core
to the system path, as shown below (add them at the very beginning of file2.py
):
import sys,os
sys.path.append(path_to_core.py)
Or, if you would run it using command line, you could simply put the following at the beginning of file2.py
import sys,os
sys.path.append(os.path.join(os.path.dirname(__file__),'../'))
Here, os.path.join(os.path.dirname(__file__),'../')
is to state the path to file2.py
.
Post a Comment for "Import Python File In Another Directory Failed"