【问题标题】:Python: 'ModuleNotFoundError' when trying to import file from same directoryPython:尝试从同一目录导入文件时出现“ModuleNotFoundError”
【发布时间】:2026-01-20 10:15:01
【问题描述】:

运行 Python 3.10。我在同一个名为 Chess 的目录中有三个文件,其中一个是 __init __.py,以确保它被视为一个模块。

在一个文件 ChessMain.py 中有一行: from Chess import ChessEngine

当我运行文件时,我得到 ModuleNotFoundError: No module named 'Chess' error.

对不起,如果这是一个愚蠢的导入问题,但我似乎无法弄清楚我做错了什么。

【问题讨论】:

  • 你可以试试from .Chess import
  • 在没有 Chess 父级的情况下尝试 import ChessEngine
  • 这取决于您调用脚本的方式和位置。现在,Python 寻找一个模块 Chess 并尝试导入。如果您在Chess 中运行,则该文件夹|模块不存在,因此会出错。要么在 Chess,cd .. && python Chess/ChessMain.py 之外调用你的脚本,要么使用 set PYTHONPATH 告诉 Python 它应该在哪里查看

标签: python python-3.x python-import


【解决方案1】:

This Might help

通常当我从同一目录导入模块时,假设

module_1.py

Modile_2.py

如果我想将它导入到我的 ma​​in.py 文件中,我只需使用

import module_name

【讨论】:

    【解决方案2】:

    如果它们在同一个目录中,那么您应该能够根据其名称从文件中导入类或函数:

    from Chess import <class-name>
    

    如果这不起作用,您可以尝试(正如其他人所说):

    from .Chess import <class-name>
    

    或者你可以试试:

    from sys import path
    path.append(<absolute-path-to-your-directory>)
    from Chess import <class-name>
    

    第一个示例在 python 3.7.3 中对我来说很好。

    【讨论】:

    • 建议不要乱用sys.path。使用PYTHONPATH=path\to\directory python main.py
    • 但有时您无法控制环境变量。