从 path/folder 加载 py 文件

load py file from path/folder

我忙于 Python 中的一些计算,因此我有一些脚本。 我试图通过名为 scriptstests 的 2 个文件夹来清理它。 现在我的问题是我的主 Python 文件无法识别子文件夹中的脚本。
所以我的 import filename 不再工作了。当我查看一些 git 文件时,它看起来像 don 提到的路径但仍然有效。
我看过 this SE question 但那给了我一个错误 (ImportError: No module named "filename")

我在主脚本、子文件夹或子文件夹中的文件中需要做什么。

我的脚本还没有 类...可能不会全部变成 类。所以通用解决方案是最好的

您可以从您所在的位置进行相对导入。假设您要从文件 /home/janbert/projects/test/test.py

导入

如果你想导入 /home/janbert/projects/test/subdir/file.py 你写:

from subdir import file

如果你想导入 /home/janbert/projects/otherproject/subdir/file.py 你写:

from ..otherproject.subdir import file

请记住每个python包(即文件夹)必须有一个名为__init__.py的文件(可以为空),否则您无法从该包中导入。