I am a beginner with Python. Before I start, here is my python folder strcuture.
-project
---main.py
---secondary-folder
----------new_main.py
---model
----------__init__.py
----------abc.py
Under project
folder I have a model
folder which has two python files __init__.py
and abc.py
which contents follow:
class ABC:
def print_abc(self):
print("abc")
Next in my main.py
and new_main.py
are the same contents:
from model.abc import ABC
if __name__ == "__main__":
ABC().print_abc()
Whenever I run python3 ./secondary-folder/new_main.py
under project
folder it results in the error:
Traceback (most recent call last):
File "./secondary-folder/new_main.py", line 1, in <module>
from model.abc import ABC
ModuleNotFoundError: No module named 'model'
But the terminal can print out abc
if I run main.py
under project
folder.
Is there anything I missed?
CodePudding user response:
If you try to import something the code is seeking from the folder you have run the file in.
So in folder secondary-folder
you have no module (folder) named model
. You have to leave that folder with calling parent folder, project
in this case.
Try this in new_main.py
:
from project.model.abc import ABC
if __name__ == "__main__":
ABC().print_abc()
CodePudding user response:
After I do some researches, I have got an idea from this link beyond top level package error in relative import
All project folders have to add ini.py like the structure below:
-project
---__init__.py
---main.py
---secondary-folder
----------__init__.py
----------new_main.py
---model
----------__init__.py
----------abc.py
Then run the command python secondary-folder.new_main
Everything will be fine.