首页 > 解决方案 > 导入的模块导入子模块失败

问题描述

我有以下文件夹结构

premier_league/
 |_cli_stats/
    |__ __init__.py
    |__cli_stats.py
    |__get_data/
         |__get_stats.py
         |__get_id.py
         |__api_scraper/
              |__api_scraper.py

cli_stats.py我有以下导入:

from get_data.get_stats import SeasonStats

get_stats.py我有以下导入:

from api_scraper.api_scraper import Football.

python cli_stats.py从文件夹运行cli_stats时会出现以下错误。

  File "cli_stats.py", line 36, in <module>
    from get_data.get_stats import SeasonStats
  File "/Users/name/Desktop/Projekt/premier_league_api/cli_stats/get_data/get_stats.py", line 12, in <module>
    from api_scraper.api_scraper import Football
ModuleNotFoundError: No module named 'api_scraper'

但是python get_stats.pyget_data文件夹运行时,导入成功。cli_stats.py为什么从文件夹运行时导入不起作用cli_stats

标签: pythonpython-3.xmodulepython-import

解决方案


您必须将导入调整为相对的。从get_stats.py你必须步入目录。错误是from api_scraper.api_scraper import Football绝对导入。

尝试:在 get_stats.py

from .api_scraper.api_scraper import Football

(api_scraper 前 1 个点)


推荐阅读