Python导入同目录辅助.py文件遇ModuleNotFoundError的解决求助
解决同目录Python脚本导入失败问题
核心问题分析
你的主脚本和辅助脚本都在/Users/myusername/Desktop/abd-datatable/src目录下,但Python找不到模块,本质是运行时的Python路径(sys.path)不包含目标模块所在目录,或者PyCharm的项目根目录配置有误。
分步解决方案
1. 先确认运行时的工作目录
在主脚本开头添加代码,打印当前工作目录:
import os print("当前工作目录:", os.getcwd())
- 如果输出是
/Users/myusername/Desktop/abd-datatable/src:说明工作目录正确,问题出在PyCharm配置或脚本本身。 - 如果输出是上级目录
/Users/myusername/Desktop/abd-datatable:说明运行时不在src目录下,需要调整导入方式或路径。
2. 针对不同运行场景的正确导入方式
场景A:直接在src目录下运行脚本
- 终端操作:先cd到src目录,再执行
python main.py - 导入代码直接用:
import helper1 as fdh import helper2 as hdh # ... import helper5 as constants - PyCharm配置:右键src目录 → Mark Directory as → Sources Root,让PyCharm识别该目录为代码根目录。
场景B:从上级目录(abd-datatable)运行脚本
比如执行python src/main.py或在PyCharm中把工作目录设为abd-datatable:
方法一:用相对导入(需主脚本作为模块运行)
导入代码改为:from . import helper1 as fdh from . import helper2 as hdh # ... from . import helper5 as constants注意:这种方式必须用
python -m src.main运行(不能直接python src/main.py)。方法二:手动将src目录加入Python路径
在主脚本开头添加:import sys import os # 获取当前脚本所在的src目录绝对路径 src_dir = os.path.dirname(os.path.abspath(__file__)) if src_dir not in sys.path: sys.path.append(src_dir) # 之后正常导入 import helper1 as fdh # ...这种方式兼容任何运行目录,因为是直接把src目录加入Python搜索路径。
3. 修正你之前的错误尝试
import src.helper1:需要src目录下有__init__.py(空文件即可,把src变成Python包),且运行目录在abd-datatable。如果满足这两个条件,这个写法是可行的,但不如上面的方法直接。from src import src.helper1:语法错误,正确写法是from src import helper1 as fdh(同样需要src是包+运行目录在上级)。
4. PyCharm额外配置检查
- 打开File → Project Structure,确认src目录在Sources列表中。
- 打开运行配置(右上角Run按钮旁边的下拉框 → Edit Configurations),检查Working directory是否设置正确:如果要直接运行主脚本,设为src目录;如果要从上级目录运行,设为abd-datatable目录。
内容的提问来源于stack exchange,提问作者triple_r
相关产品推荐
相关产品推荐

