- Python get root path
- # Table of Contents
- # Get the path of the Root Project directory using Python
- # Getting a path to a file located in the project’s root directory
- # Importing the ROOT_DIR variable in another file
- # Get the path of the Root Project directory using pathlib.Path
- # Dynamically getting the root project folder from any directory
- # Using the os.curdir constant to get the root project directory
- # Additional Resources
- Python — Get Path of Root Project Structure
- Finding File Relative to Project Root in Python
- Why is python assuming my path is the project root, which is two directory levels up?
- Getting absolute path when trying to get root directory
- Python — Loading files relative from project root
- How do I get the parent directory in Python?
Python get root path
Last updated: May 11, 2023
Reading time · 4 min
# Table of Contents
# Get the path of the Root Project directory using Python
To get the path of the root project directory:
- Use the os.path.abspath() method to get a normalized absolute path to the current file.
- Use the os.path.dirname() method to get the directory name of the path.
For example, suppose we have the following project structure.
Copied!my-project/ └── main.py └── another.py └── example.txt
You can add the following code to main.py to get the path to the root project directory.
Copied!import os # 👇️ /home/borislav/Desktop/bobbyhadz_python/main.py print(__file__) ROOT_DIR = os.path.dirname( os.path.abspath(__file__) ) # 👇️ /home/borislav/Desktop/bobbyhadz_python print(ROOT_DIR)
The __file__ variable is set to the module’s path.
We used the os.path.abspath() to get a normalized absolute version of the path.
The last step is to pass the absolute path to the os.path.dirname method.
The method returns the directory name of the supplied path.
Since our main.py file is located in the root directory of the project, the ROOT_DIR variable stores the path to the project’s root directory.
If your file is located one directory deep, you can call os.path.dirname() two times.
For example, suppose you have the following folder structure.
Copied!my-project/ src/ └── constants.py
Copied!import os ROOT_DIR = os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) # 👇️ /home/borislav/Desktop/bobbyhadz_python print(ROOT_DIR)
Notice that we called the os.path.dirname() method twice to get the root project directory, because the constants file is located in a nested directory.
# Getting a path to a file located in the project’s root directory
The same approach can be used to get the path to a file that’s located in the project’s root directory.
Suppose we have the following folder structure and we want to get the path to the example.txt file.
Copied!my-project/ └── main.py └── another.py └── example.txt
You have to pass the ROOT_DIR variable and the example.txt string to the os.path.join() method to combine the two paths.
Copied!import os ROOT_DIR = os.path.dirname( os.path.abspath(__file__) ) # 👇️ /home/borislav/Desktop/bobbyhadz_python print(ROOT_DIR) PATH_TO_FILE_IN_ROOT_DIR = os.path.join(ROOT_DIR, 'example.txt') # 👇️ /home/borislav/Desktop/bobbyhadz_python/example.txt print(PATH_TO_FILE_IN_ROOT_DIR)
The os.path.join method takes a path and one or more path segments and joins them intelligently.
The method returns the concatenation of the supplied path and path segments.
# Importing the ROOT_DIR variable in another file
You can store your ROOT_DIR variable in a file from which you import your constants and import it into other files.
Suppose we have the following folder structure.
Copied!my-project/ └── main.py └── another.py └── example.txt
This is the code for the main.py file where the ROOT_DIR variable is defined.
Copied!import os ROOT_DIR = os.path.dirname( os.path.abspath(__file__) ) # 👇️ /home/borislav/Desktop/bobbyhadz_python print(ROOT_DIR) PATH_TO_FILE_IN_ROOT_DIR = os.path.join(ROOT_DIR, 'example.txt') # 👇️ /home/borislav/Desktop/bobbyhadz_python/example.txt print(PATH_TO_FILE_IN_ROOT_DIR)
Here is how you can import the ROOT_DIR and PATH_TO_FILE_IN_ROOT_DIR variables into a different file.
Copied!from main import ROOT_DIR, PATH_TO_FILE_IN_ROOT_DIR # 👇️ /home/borislav/Desktop/bobbyhadz_python print(ROOT_DIR) # 👇️ /home/borislav/Desktop/bobbyhadz_python/example.txt print(PATH_TO_FILE_IN_ROOT_DIR)
The another.py module is located in the same directory as the main.py file that defines the ROOT_DIR variable.
# Get the path of the Root Project directory using pathlib.Path
You can also use the Path class from the pathlib module to get the path to the root project directory.
Suppose we have the following folder structure.
Copied!my-project/ └── main.py └── src/ └── constants.py
Here is the code for constants.py .
Copied!from pathlib import Path def get_project_root_dir(): return Path(__file__).absolute().parent.parent
The module uses the pathlib.Path() class to get the absolute path to the current module and uses the parent attribute to get the logical parent of the path.
Now you can import and use the get_project_root_dir function into your main.py file.
Copied!from src.constants import get_project_root_dir ROOT_DIR = get_project_root_dir() # 👇️ /home/borislav/Desktop/bobbyhadz_python print(ROOT_DIR)
Here is an example that better illustrates how the parent attribute works.
Copied!from pathlib import Path abs_path = Path(__file__).absolute() # /home/borislav/Desktop/bobbyhadz_python/main.py print(abs_path) print(abs_path.parent) # 👉️ /home/borislav/Desktop/bobbyhadz_python print(abs_path.parent.parent) # 👉️ /home/borislav/Desktop print(abs_path.parent.parent.parent) # 👉️ /home/borislav
You can access the parent attribute multiple times to get the logical parent of each path.
Accessing the attribute once removes the filename.
The second time you access the attribute, the folder that contains the file is removed and so on.
# Dynamically getting the root project folder from any directory
This approach can be made more flexible by using a generator expression that looks for the root directory by name.
Copied!from pathlib import Path current_dir = Path(__file__) PROJECT_NAME = 'bobbyhadz_python' ROOT_DIR = next( p for p in current_dir.parents if p.parts[-1] == PROJECT_NAME ) # 👇️ /home/borislav/Desktop/bobbyhadz_python print(ROOT_DIR)
Notice that you have to specify the name of your project.
In my case, the project is named bobbyhadz-python .
The generator expression iterates over the parent directories and checks if the last part of each parent directory is equal to the project name.
If the condition is met, then we are in the root directory of the project.
# Using the os.curdir constant to get the root project directory
If you run your Python script from the root project folder, you can also:
- Use the os.curdir attribute to get a string that is used to refer to the current directory.
- Pass the string to the os.path.abspath() method.
Copied!import os ROOT_DIR = os.path.abspath(os.curdir) # 👇️ /home/borislav/Desktop/bobbyhadz_python print(ROOT_DIR)
The code sample assumes that your main.py module is placed in the root directory of your project and you run the file from the same directory.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Python — Get Path of Root Project Structure
The project_root is set to the folder above your script’s parent folder, which matches your description. The output folder then goes to subfolder1 under that.
I would also rephrase my import as
from os.path import dirname, join
That shortens your code to
project_root = dirname(dirname(__file__))
output_path = join(project_root, 'subfolder1')
I find this version to be easier to read.
Finding File Relative to Project Root in Python
This would be a different answer if it were results.py and the question were «How do you import that from here,» but «How do you load that» is pretty straightforward.
Remember that __file__ is the relative path from your curdir to the python file it’s being executed in. This lets us calculate the path in two ways: one using the modern pathlib stdlib library and one with os commands.
# using pathlib
from pathlib import Path
thisfile = Path(__file__)
programs = thisfile.parent
project1 = programs.parent
data = project1 / 'data' # yep, we're dividing by a string. pathlib is awesome
resultscsv = data / 'results.csv'
# or
resultscsv = Path(__file__).parent.parent / 'data' / 'results.csv'
# using os
import os.path
thisfile = os.path.abspath(__file__)
programs = os.path.dirname(thisfile)
project1 = os.path.dirname(programs)
data = os.path.join(project1, 'data')
resultscsv = os.path.join(data, 'results.csv')
# or
resultscsv = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', 'results.csv')
# or POSSIBLY, but this might not work in all places
resultscsv = os.path.join(__file__, '..', '..', 'data', 'results.csv')
The pathlib approach looks massively more readable to me, and is compounded with the fact that then opening the file becomes:
with resultscsv.open(mode='r') as f:
.
rather than the (slightly) more obtuse
with open(resultscsv, mode='r') as f:
.
Why is python assuming my path is the project root, which is two directory levels up?
According to https://code.visualstudio.com/docs/python/settings-reference :
Indicates whether to run a file in the file’s directory instead of the current folder.
So presumably just set python.terminal.executeInFileDir to true .
Getting absolute path when trying to get root directory
cd ../ is change directory command which can be used to go back in directory tree.
example:
If you are in /home/user.com/src/iform/dvops/build_iform_app/src , then command
cd ../../../../ will change you current working directory to /home/user.com/src/ .
In string notation, if ROOT_DIR is giving you /home/user.com/src/iform/dvops/build_iform_app/src , then ROOT_DIR/../../../../ should correspond to /home/user.com/src/ , which you want.
Python — Loading files relative from project root
I like to create some sort of configuration file in the project root that has an aboslute path to the root. I do this only because the frameworks i usually use (django, scrapy) have some sort of convention like this
├ .
├── pve
│ ├── blahblah
│ │ ├── TestDefinition.py
│ │ ├── TestDefinition.pyc
│ │ ├── __init__.py
│ │ └── __init__.pyc
│ └── pve.py
├── src
│ └── definitions
│ └── THISFILE.yml
└── settings.py
# settings.py
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DEFINITIONS_ROOT = os.path.join(PROJECT_ROOT, 'src', 'definitions')
from myproject import settings
settings.DEFINITIONS_ROOT
How do I get the parent directory in Python?
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent.absolute())
import os
print os.path.abspath(os.path.join(yourpath, os.pardir))
where yourpath is the path you want the parent for.