When you are trying to execute a Python script which is not present directly at the project root folder and you are trying to import a module present at the root directory, you may get an import error like below.
ModuleNotFoundError: No module named 'YourModuleName’
To avoid the above issue, we need to add the project root directory to the Python search path. Instead of dynamically adding the project root directory during each run, there is a way to add it permanently.
Permanently Adding Project Root Directory to Python Search Path
For example, if your project folder structure is as below, where .venv is the location of your python virtual environment.
- Project Root
- .venv
- module 1
- module 2
To add the project root directory to the Python search path, create a file called ‘projectPath.pth’ at
.venv\Lib\site-packages\projectPath.pth
Open above file in Notepad and add the project root directory path. For adding multiple paths, use separate lines for each path. The path can either be specified absolute or relative.
Using Relative Path in *.pth File
For the below folder structure,
- Project Root
- .venv
- Lib
- site-packages
- projectPath.pth
- site-packages
- Lib
- module 1
- .venv
The relative path to add the project root directory to Python is
..\\..\\..\\
Reference
Know of a better way to add the project root directory to Python? Do let us know in the comments :-)
No comments:
Feel free to leave a piece of your mind.