3

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

Currently, I'm programming in PyCharm and the IDE does not show any warnings or problems. It even autocompletes the code above. Nonetheless, when I want to run new_file.py in the command line it throws the following error:

ModuleNotFoundError: No module named 'assignment01'
Marcello Zago
  • 629
  • 5
  • 19

2 Answers2

2

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.

2e0byo
  • 5,305
  • 1
  • 6
  • 26
  • Sorry, I forgot to show, that I have also a ```__init__.py``` in the projects directory. Now, if I import it with ```from ..assignment01 import old_file```, I get the following error: ```ImportError: attempted relative import with no known parent package``` – Marcello Zago Oct 28 '21 at 10:31
  • @MarcelloZago yes, for relative imports you need to be calling from the root package (or at least above the relative level). I'l update – 2e0byo Oct 28 '21 at 10:36
0

Add another __init__.py in the project directory.

Also, with your code, try running new_file.py from your project directory.

Example:

python assignment02/new_file.py
Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22