'Python: 'ModuleNotFoundError' when trying to import file from same directory
Running 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.
In one file, ChessMain.py I have a line:
from Chess import ChessEngine
When I run the file, I get the
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.
Solution 1:[1]
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:
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.
Solution 2:[2]
Let's say, this is my directory content
\_ module_1.py
\_ module_2.py
\_ main.py
And if I want to import it into my main.py file, I simply use
import module_1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TwoFace |
Solution 2 | GC 13 |