Problem: I want to import a file in the same folder
Problem 2: I want to import a file from a subfolder
Solution: Add folder path to Python’s sys.path
Sample layout
my_package | |----__init__.py |----myapp.py |----client.py |----/utils |--------__init__.py |--------client_tools.py
With the following pattern in myapp.py
from client import ClientClass
Yet Python will argue
ModuleError: No module named 'client'
Yet clearly client.py is right there in the same folder. What gives?
Solution: Add info to the folder’s __init__.py
For each folder having Python files in them, add the following to the init files:
import os, sys sys.path.append(os.path.dirname(os.path.realpath(__file__)))
When Python sees the init files, it’ll now register the directory in the system path, which is where it looks to find modules/files/packages being imported.
So now in myapp, both of these imports will work
from client import ExampleClass from utils.client_tools import AnotherClass