Python跨文件夹导入报错ModuleNotFoundError: No module named 'Teacher'
解决ModuleNotFoundError: No module named 'Teacher'的问题
方法1:调整脚本运行目录
在项目根目录(D:\Devang\PYTHON PW SKILLS)下执行命令运行脚本,不要在Student文件夹内运行:
python Student/student_details.py
此时Python会自动将根目录加入模块搜索路径,你的导入语句from Teacher import teacher_details就能正常识别Teacher文件夹。
方法2:在脚本中正确添加上级目录到搜索路径
如果必须在Student文件夹内运行脚本,需要在导入代码之前将上级目录添加到sys.path中,修改后的student_details.py代码如下:
import sys # 将上级目录(包含Teacher和Student的目录)添加到模块搜索路径 sys.path.append('../') from Teacher import teacher_details class Student: print("This is a student class") teacher_details.teacher()
注意:sys.path.append('..')必须写在导入语句之前,否则Python在搜索模块时还未加载该路径,无法生效。
问题原因说明
你的导入语句本身没有错误,报错的核心原因是:
- 当在Student文件夹内运行脚本时,Python默认的模块搜索路径仅包含当前文件夹(Student),无法找到同级的Teacher文件夹;
- 你之前尝试添加
sys.path.append('..')如果位置错误(比如在导入语句之后),就无法起到修改搜索路径的作用。
内容的提问来源于stack exchange,提问作者Devang soni
相关产品推荐
相关产品推荐

