Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModuleNotFoundError when importing local module from sub folder in Python [duplicate]

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.

like image 359
T Pol Avatar asked May 13 '26 13:05

T Pol


1 Answers

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

like image 163
D_Gamer Avatar answered May 15 '26 04:05

D_Gamer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!