【问题标题】:how to import file.py from main folder if you are working in a subfolder python3如果您在子文件夹 python3 中工作,如何从主文件夹导入 file.py
【发布时间】:2026-02-21 23:40:01
【问题描述】:

我有一个这样的结构:

/mainfolder
file.py
    //subfolder
    test.py

我正在尝试将file.py 导入test.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()])

也不行

【问题讨论】:

  • 旁注:您应该使用包而不是文件夹

标签: python python-3.x import python-import


【解决方案1】:

看起来您正在运行 test.pypython test.py,因此 test 模块被视为*模块。

如果你的文件夹不是 Python 包,你应该首先添加 __init__.py 文件:

/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 没有相对导入工作。警惕通配符导入。

请参阅 ModuleNotFoundError: What does it mean __main__ is not a package?How to do relative imports in Python? 了解更多关于您当前的方法为何不起作用的信息。

【讨论】:

  • 假设我在 //subfolder 中有一个 test2.py 并且 test.py 在开始时有 from file import *,我如何在 test2.py 中导入 test.py?
  • 丢弃import *。明确指定要导入的内容。如果subfolder 是一个子包,那么import .testfrom mainfolder.subfolder import test 应该没问题
【解决方案2】:

您使用的是什么 IDE?我正在使用带有 Python 3 的 Pycharm 社区 IDE,它适用于 from file import *from file import some_function(我想发表评论,但我不能发表评论,因为我还没有 50 名声望)

【讨论】: