如果您在子文件夹 python3 中工作,如何从主文件夹导入 file.py

how to import file.py from main folder if you are working in a subfolder python3

我有这样的结构:

/mainfolder
file.py
    //subfolder
    test.py

我正在尝试在 test.py 中导入 file.py。出于某种原因,我不能。

我试过了

from .file import *

返回:

Traceback (most recent call last):
ModuleNotFoundError: No module named '__main__.file'; '__main__' is not a package

还尝试将路径添加到 sys.path:

import sys
import os
sys.path.extend([os.getcwd()])

也不行

你在用什么IDE?我正在使用 Pycharm Community IDE 和 Python 3,它可以与 from file import *from file import some_function 一起使用(我想发表评论,但我不能,因为我没有还没有 50 声望)

看起来您是 运行 test.pypython test.py,因此 test 模块被视为顶级模块。

您应该首先通过添加 __init__.py 个文件将您的文件夹 Python 打包:

/mainfolder
__init__.py
file.py
    /subfolder
    __init__.py
    test.py

然后你可以将外部 mainfolder 附加到 sys.path:

import sys
import os
sys.path.append(os.path.join(os.getcwd(), '..'))

之后 from file import someobject 没有相对导入工作。警惕外卡进口。

请参阅 and How to do relative imports in Python? 以详细了解为什么您当前的方法不起作用。