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

时间:2017-05-02 14:59:45

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

我有一个结构:

/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()])

不起作用

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您似乎正在使用test.py运行python 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工作。警惕外卡进口。

请参阅ModuleNotFoundError: What does it mean __main__ is not a package?How to do relative imports in Python?,详细了解当前方法无效的原因。