2

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.

T Pol
  • 23
  • 1
  • 4

2 Answers2

3

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

D_Gamer
  • 168
  • 12
  • that's work! but how can I insert parent directory? ```sys.path.insert(0, '..')``` doesn't seem to work. – T Pol Aug 23 '21 at 15:45
  • 2
    yeah, you can use os Module to get current working directory and then can also fetch parent directory from it ```python import os # get current directory path = os.getcwd() print("Current Directory", path) print() # parent directory parent = os.path.dirname(path) print("Parent directory", parent) ``` – D_Gamer Aug 24 '21 at 15:28
0

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)
Sylvaus
  • 844
  • 6
  • 13
  • Thank you for the explanation. I would go for the first options for simplicity. Together with @D_Gamer sys path hack I think I got the whole idea. – T Pol Aug 23 '21 at 15:49