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

Python项目导入子模块报错求助:module 'code' has no attribute 'text'

问题描述

项目文件结构如下:

📁 code 
├── 📁 text 
│   ├── 📄 __init__.py
│   ├── 📄 style.py
│   ├── 📄 font.py
│   └── 📄 rendering.py
└── 📁 button 
    ├── 📄 __init__.py
    ├── 📄 style.py
    └── 📄 rendering.py

📁 data  
└── 📁 images
    ...

📄 main.py

已在code/text和code/button目录添加__init__.py,但在main.py中导入code/text/style.py时,提示错误:"module 'code' has no attribute 'text'"。

解决方案

1. 给code目录补充__init__.py

code作为父包,必须在其根目录(和text、button同级的位置)添加空的__init__.py文件,否则Python不会将它识别为可导入的包。

2. 使用正确的导入语句

在main.py中导入style.py的正确写法:

  • 绝对导入(推荐):
    from code.text import style
    # 或者导入具体函数/类
    from code.text.style import your_target_function
    
  • 相对导入(主脚本不建议使用,仅作参考):
    from .code.text import style
    

3. 检查Python模块搜索路径

如果运行main.py时,项目根目录不在Python的模块搜索路径中,也会导致找不到包。可以在main.py开头添加以下代码排查:

import sys
print(sys.path)

若项目根目录不在输出列表中,手动添加:

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent))

4. 核心修复:重命名code目录

code是Python的内置模块,用这个名字作为自定义包名会直接引发命名冲突——Python会优先加载内置的code模块,完全不会识别你的自定义包,这大概率是报错的根本原因。

直接将code目录重命名为app_code、ui_code这类无冲突的名称,再修改导入语句,比如:

from app_code.text import style

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:40:47