ModuleNotFoundError when importing local module from sub folder in Python

4.4k Views Asked by At

File Organization

./helper.py
./caller1.py
./sub_folder/caller2.py

It's fine when importing helper.py from caller1.py.

caller1.py

from helper import hello
if __name__ == '__main__':
    hello()

but when importing from ./sub_folder/caller2.py with the exact same code I got the error...

ModuleNotFoundError: No module named 'helper'

I would like to organize files into sub-folders because the project is quite large.

2

There are 2 best solutions below

1
Sylvaus On BEST ANSWER

You have to understand how Python finds the modules and packages when using import.

When you execute a python code, the folder in which this file is will be added to the PYTHONPATH which is the list of all the places where python will look for your packages and modules.

When you call caller1.py, it works because helper.py is in the same folder but it does not work for caller2.py because python does not find it in the same folder nor the other path in PYTHONPATH.

You have three options:

  • call caller2.py from a script in the same folder as helper
  • add the folder containing helper.py in the PYTHONPATH (not recommended)
  • make your code into a package that you can pip install -e, this way python will be able to find your modules as they will be install in the site-packages of your python environment (most complex but cleanest solution)
2
D_Gamer On

As a solution for this, You can add the path of that file in system using sys module and then you can import that perticular file.

like in your case

caller2.py

import sys
sys.path.insert(0, "C:/Users/D_Gamer/Desktop/pyProject/helperDir")
# You need to provide path to the directory in which you have a helper file so basically I have "helper.py" file in "helperDir" Folder

from helper import hello

if __name__ == '__main__':
    hello()

There are other ways to achieve the same but for now you can hold onto this and for more information checkout this reference on Github