我有这个文件夹结构:
--test
first.py
--numpad
second.py
third.py
在第一个.py 中我有这行代码:
from numpad import second
在第二个.py 文件中我有这个:
import third
但是当我运行时在测试文件夹中
python first.py
我收到此错误消息:
ModuleNotFoundError:没有名为“third”的模块
注意:我也尝试将 __init__.py
添加到我的小键盘文件夹中,但它不起作用
最佳答案
由于 python 解释器是在 test
中启动的,因此它就是在其中查找导入的。您可以通过the docs了解pythons对导入的搜索行为,如果您对详细信息感兴趣。
要解决您的问题,有很多方法可以实现,最好的方法取决于您计划如何使用代码。如果您打算编写一个库,package it 可能有意义。 ,这将使您能够访问可以使用的全局命名空间。
但是,如果您只想让它立即工作,并且只从同一个位置(即您的 test
文件夹)运行解释器,请定义 第三个
作为本地文件应该这样做:
第二个.py
from . import third
第三.py
print('third here, not an import error')
这对我有用:
~/test$ tree .
.
├── first.py
└── numpad
├── second.py
└── third.py
~/test$ python3.6 first.py
third here, not an import error
关于python - 尝试从另一个文件夹导入时找不到模块错误问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56456959/