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

Python跨目录导入函数失败:ModuleNotFoundError报错求助

解决ModuleNotFoundError: No module named 'new_structure'

问题场景

目录结构:

.
├── GNS
│   └── gns_export.py
└── new_structure
    └── DB_Manager.py

在gns_export.py中执行from new_structure.DB_Manager import *时,出现ModuleNotFoundError: No module named 'new_structure'错误。

解决方案

方法1:手动添加父目录到模块搜索路径

在gns_export.py的最开头添加以下代码,将项目根目录(包含GNS和new_structure的目录)加入Python的模块搜索路径:

import sys
import os
# 获取当前脚本所在目录的父目录
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(root_dir)

# 之后正常导入
from new_structure.DB_Manager import *

方法2:从项目根目录运行脚本

打开终端,切换到包含GNS和new_structure的根目录,然后执行:

python GNS/gns_export.py

这种方式下,Python会自动将当前运行目录(根目录)加入模块搜索路径,从而识别到new_structure模块。

方法3:将new_structure转为Python包

在new_structure文件夹中创建一个空的__init__.py文件(让Python将其识别为可导入的包),之后结合上述两种方法之一即可正常导入。

内容的提问来源于stack exchange,提问作者Clemens Hodina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:22:35