Python
Project Structure
File Path
Root Directory
Programming Tips

Python get project root directory with Path(__file__).resolve()

Codemia Knowledge Hub ·

To get a Python project's root directory reliably, build it from the current file with Path(__file__).resolve().parent (adding .parent steps as needed), search upward for a marker file such as pyproject.toml or .git, or read it from an environment variable. Do not rely on os.getcwd(): the working directory depends on how the script is launched, so relative paths built from it raise FileNotFoundError in other environments.

Using pathlib and __file__

python
1from pathlib import Path
2
3# Get the directory containing the current script
4SCRIPT_DIR = Path(__file__).resolve().parent
5
6# Navigate up to the project root (assumes script is in src/utils/)
7PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
8
9# Access a file relative to the project root
10config_path = PROJECT_ROOT / "config" / "settings.json"
11data_path = PROJECT_ROOT / "data" / "input.csv"
12
13print(PROJECT_ROOT)   # /home/user/my-project
14print(config_path)    # /home/user/my-project/config/settings.json

Path(__file__).resolve() gives the absolute path of the current file, and each .parent walks one level up. This is the simplest option when you know where the file sits relative to the root.

Call .resolve() immediately. Without it, __file__ may be a relative path like ./src/main.py, which becomes invalid if the working directory changes later (for example with os.chdir()).

Hardcoded .parent chains break when the file moves to a different directory depth. The next two approaches avoid that.

Finding the root by marker file

python
1from pathlib import Path
2
3def find_project_root(marker_files=("pyproject.toml", "setup.py", ".git")):
4    """Walk up from the current file until a marker file is found."""
5    current = Path(__file__).resolve().parent
6    while current != current.parent:
7        for marker in marker_files:
8            if (current / marker).exists():
9                return current
10        current = current.parent
11    raise FileNotFoundError("Project root not found")
12
13ROOT = find_project_root()
14print(ROOT)  # /home/user/my-project

This walks upward until it finds pyproject.toml, setup.py or a .git directory, so it works however deeply the calling script is nested.

A dedicated root module

python
1# project_root/__init__.py (or root_config.py at the project root)
2from pathlib import Path
3
4ROOT_DIR = Path(__file__).resolve().parent
5
6# Usage from any module:
7# from project_root import ROOT_DIR
8# config = ROOT_DIR / "config" / "app.yaml"

A small module at the project root exports ROOT_DIR, and other modules import it. The root logic lives in one place instead of .parent.parent chains scattered through the codebase.

Using os.path in older code

python
1import os
2
3# Get directory of current script
4SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
5
6# Navigate up two levels
7PROJECT_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, "..", ".."))
8
9# Join paths
10config_path = os.path.join(PROJECT_ROOT, "config", "settings.json")
11
12print(PROJECT_ROOT)
13print(config_path)

pathlib.Path is preferred in modern Python (3.4+) for its cleaner, object-oriented API, but os.path is still common in legacy code.

Using environment variables

python
1import os
2from pathlib import Path
3
4# Set in shell: export PROJECT_ROOT=/home/user/my-project
5# Or in .env file with python-dotenv
6
7ROOT = Path(os.environ.get("PROJECT_ROOT", Path(__file__).resolve().parent.parent))
8config = ROOT / "config" / "app.yaml"
9
10# With python-dotenv
11from dotenv import load_dotenv
12load_dotenv()  # loads .env from the calling script's directory or its parents
13ROOT = Path(os.environ["PROJECT_ROOT"])

An environment variable decouples the root path from the code layout, which is common in containerized deployments where the root differs between local development and production.

Working directory vs script directory

python
1import os
2from pathlib import Path
3
4# These are DIFFERENT:
5cwd = os.getcwd()                            # where you ran the command from
6script_dir = Path(__file__).resolve().parent  # where the script file lives
7
8# Example: running "python src/app/main.py" from /home/user/my-project
9# cwd        = /home/user/my-project
10# script_dir = /home/user/my-project/src/app
11
12# Running the same script from a different directory:
13# cd /tmp && python /home/user/my-project/src/app/main.py
14# cwd        = /tmp
15# script_dir = /home/user/my-project/src/app  (unchanged)

The working directory is controlled by the caller, so use __file__-based paths to locate project files.

  • No __file__: in the Python REPL, Jupyter notebooks and some frozen executables, __file__ is not defined. Guard with getattr(sys.modules[__name__], '__file__', None), or fall back to os.getcwd() in those contexts.
  • Symlinks: Path(__file__).parent is a purely lexical operation and does not follow symlinks, but resolve() does. If your project uses symlinked files, resolve() returns the real path, which may be outside the expected directory tree, so check for symlinks explicitly.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms