I’m trying to import Entity.py into Tower.py in the same directory, in order to instantiate the Entity class inside Tower.py. However, it keeps coming up with the same error.
folder
|_ scripts
|_ Tower.py
|_ Entity.py
|_ Main.py
Entity.py
class Entity:
...
Tower.py
import Entity
File "C:\...\scripts\Tower.py", line 3, in <module>
import Entity
ModuleNotFoundError: No module named 'Entity'
I’m confused as to why this is happening and what I’m doing wrong.
>Solution :
Modules are relative to the working directory. So, if you are running the app using Main.py, every import will be relative to the directory of Main.py.
If you want to import the Entity to Tower, you must import it like
from scripts.Entity import Entity
or with relative like
from .Entity import Entity
And you must create a __init__.py file in your scripts folder to mark it as a package.