You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 13:26:08