导入自定义Python模块时遭遇ModuleNotFoundError问题求助
解决ModuleNotFoundError: No module named 'third'的问题
问题原因
运行first.py时,Python的工作目录是项目根目录(即first.py所在文件夹)。second.py里用from third import a时,Python会在sys.path包含的路径里查找third.py,但third.py在some_dir子目录下,不在全局查找路径中,因此抛出模块找不到的错误。另外你的first.py里导入的c在second.py中并未定义,实际定义的是sum,这也是后续会遇到的问题。
解决方案
方案1:相对导入(推荐,符合Python包规范)
这是包内模块间引用的标准方式:
- 在
some_dir目录下创建一个空的__init__.py文件,让Python将some_dir识别为可导入的包:
├── first.py └── some_dir ├── __init__.py ├── second.py └── third.py
- 修改
second.py中的导入语句为相对导入(.表示当前目录):
"""This is the second file. We import a variable from the third and calculate the sum of a and b""" from .third import a b = 10 sum = a + b
- 修改
first.py中的导入语句,导入正确的变量sum:
"""This is the first and final file where everything comes together""" from some_dir.second import sum print(sum)
方案2:绝对导入(基于项目根目录)
直接使用完整的包路径导入third,Python可以从项目根目录找到它:
修改second.py的导入语句:
"""This is the second file. We import a variable from the third and calculate the sum of a and b""" from some_dir.third import a b = 10 sum = a + b
同时修正first.py中的变量名:
"""This is the first and final file where everything comes together""" from some_dir.second import sum print(sum)
这种方式不需要创建__init__.py,运行first.py时根目录会自动加入sys.path,可以正常工作。
方案3:手动添加模块路径(不推荐,仅临时场景使用)
在second.py开头添加代码,将当前脚本所在目录加入Python的查找路径:
"""This is the second file. We import a variable from the third and calculate the sum of a and b""" import sys import os # 将当前脚本所在目录添加到查找路径 sys.path.append(os.path.dirname(os.path.abspath(__file__))) from third import a b = 10 sum = a + b
同样需要修正first.py中的变量名。这种方法依赖脚本位置,项目结构变动时容易出错,仅适合临时测试使用。
内容的提问来源于stack exchange,提问作者syrok
相关产品推荐
相关产品推荐

