[英]Python: 'ModuleNotFoundError' when trying to import file from same directory
Running Python 3.10.运行 Python 3.10。 I have three files in the same directory named Chess, one of which is a
__init __.py
to make sure it's considered a module.我在同一个名为 Chess 的目录中有三个文件,其中一个是
__init __.py
以确保它被视为一个模块。
In one file, ChessMain.py I have a line: from Chess import ChessEngine
在一个文件 ChessMain.py 我有一行:
from Chess import ChessEngine
When I run the file, I get the ModuleNotFoundError: No module named 'Chess' error.
当我运行该文件时,我收到
ModuleNotFoundError: No module named 'Chess' error.
Sorry if this is a dumb import question, but I can't seem to figure out what I'm doing wrong.抱歉,如果这是一个愚蠢的导入问题,但我似乎无法弄清楚我做错了什么。
Usually when I import a module from the same directory, lets say通常当我从同一目录导入模块时,可以说
module_1.py
模块_1.py
and和
Modile_2.py
模块_2.py
And if I want to import it into my main.py file, I simply use如果我想将它导入到我的main.py文件中,我只需使用
import module_name
If they are in the same directory then you should be able to import a class or function from the file based off of its name:如果它们在同一目录中,那么您应该能够根据文件名从文件中导入 class 或 function:
from Chess import <class-name>
If that doesn't work, you can try (as others have said):如果这不起作用,您可以尝试(正如其他人所说):
from .Chess import <class-name>
Or you can try:或者您可以尝试:
from sys import path
path.append(<absolute-path-to-your-directory>)
from Chess import <class-name>
The first example worked fine for me in python 3.7.3.第一个示例在 python 3.7.3 中对我来说效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.