问题
I busy with some calculations in Python and therefore i have some bunch of scripts.
I have tried to clean this up thru 2 folders named scripts
and tests
.
Now i have the problem that my main Python file don't recognize the scripts in the subfolders.
So my import filename
don't work anny more. When i look in some git files it looks like the don mention paths and still it works.
I had looked at this SE question but that gave me a error (ImportError: No module named "filename"
)
What have i to do in my main script, subfolder or files in subfolders.
my scripts are no classes yet... Probably not all become classes. so a generic solution is best
回答1:
You can do relative imports from where you are. Let's assume you're importing from the file /home/janbert/projects/test/test.py
If you want to import /home/janbert/projects/test/subdir/file.py
you write:
from subdir import file
And if you want to import /home/janbert/projects/otherproject/subdir/file.py
you write:
from ..otherproject.subdir import file
Just remember that each python package (ie folder) must have a file named __init__.py
(which can be empty), otherwise you can not import from that package.
来源:https://stackoverflow.com/questions/35245508/load-py-file-from-path-folder