I have a project with the following structure:
.
└── project
├── assignment01
| ├── __init__.py
| └── old_file.py
|
├── assignment02
| ├── __init__.py
| └── new_file.py
└── __init__.py
I need to use a function that I implemented in the first assignment in the file new_file.py
which I import as follows:
from assignment01 import old_file as assgn1
When I want to run new_file.py
in the command line it throws the following error:
ModuleNotFoundError: No module named 'assignment01'
You either need to make both assignments be part of a package, by putting a __init__.py
inside project
and then doing from ..assignment01 import old_file
. You will need to call your code from above project
(python -m project.assignment1.newfile.main
) , so python picks up the outer package and is able to resolve ..
. Or you can leave out the ..
and simply call from project
, as noted in the other answer. In any case the idea is to get assignment0
somewhere that python can find it and import.
Or you need to add project
to your sys.path
:
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
Your current import fails because python is looking in assignment02
for assignment01
and, of course, failing.