Getting the root path of a Python project can be achieved in many different ways depending on the use case. I personally use the same method on all my Python projects. It works great for me and, so far, I have never encountered a problem with it. It’s quite simple and this is how it works:
1. Create a Python file at the top-level of the project:
We’ll name this file
project/ |__ ... |__ constants.py |__ main.py |__ utils.py |__ ...
Here we define a variable that points to the project’s root directory:
from os import path ROOT_DIR = path.dirname(path.abspath(__file__))
Now you can easily access the root directory in any file of your project with the import statement:
from constants import ROOT_DIR
Of course, you can add other useful path variables like
UTILS_PATH to the
constants.py file if you need to.
That’s all. Hope you find this post useful.