首页 > 解决方案 > ModuleNotFoundError:没有名为“xyz”的模块;'xyz' 不是一个包

问题描述

我在 python 中的相对导入中遇到问题。下面是我的python3项目结构。

    .
├── production
│   ├── __init__.py
│   ├── database_connection.py
│   ├── prod-404-error-status-only.py
│   └── search_filter_criteria.py
└── utils
    ├── __init__.py
    ├── send_email_script.py
    └── utils.py

我得到的错误是

    Traceback (most recent call last):
  File "production/search_filter_criteria.py", line 11, in <module>
    from utils.utils import get_date_string, read_txt, read_xml
ModuleNotFoundError: No module named 'utils'

尝试以许多不同的方式尝试。向每个模块添加了init .py 文件,但仍然面临问题。

标签: pythonpython-3.x

解决方案


由于文件位于不同的文件夹中,因此您需要from utils.utils import get_date_string, read_txt, read_xml在行之前附加路径。

import sys
sys.path.append('/path/to/root/directory/of/project')

推荐阅读