Coding Triumph

Helpful code snippets & tutorials

How to get the root directory of a project in Python

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 constants.py:

Project structure:
project/
|__ ...
|__ constants.py
|__ main.py
|__ utils.py
|__ ...


Here we define a variable that points to the project’s root directory:

Code:
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 CONFIG_PATH or UTILS_PATH to the constants.py file if you need to.

That’s all. Hope you find this post useful.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments