load py file from path/folder

喜欢而已 提交于 2020-01-07 02:59:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!