python - 尝试从另一个文件夹导入时找不到模块错误问题

标签 python python-3.6

我有这个文件夹结构:

--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/

相关文章:

python - 如果传入选项,则将值设置为 argparse 中的变量

python - 使用 pyenv 在系统范围内安装特定版本的 Python

python - Popen.stdout.readline() 在 Python 3.2 中工作,但在 Python 3.6 中返回空字符串

Python Win 3.6.0 x64 问题,在 pip3 安装 pyqt5 后缺少 qt designer exe

python - 将具有 latin-1 字符的字节解码为具有十进制表示的字符串

python - 限制类属性值的可能选项

python - 使用 Pandas Align 时,时间序列数据帧返回错误 - valueError : cannot join with no overlapping index names

python - Python3 中的 http.client.IncompleteRead 错误

python - X数组 : add a "layer" of data to NetCDF

javascript - 使用 JS/CSS 缩小工具作为 python distutils 命令?