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__
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
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
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
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
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
The working directory is controlled by the caller, so use __file__-based paths to locate project files.
When __file__ is undefined or points through a symlink
- No
__file__: in the Python REPL, Jupyter notebooks and some frozen executables,__file__is not defined. Guard withgetattr(sys.modules[__name__], '__file__', None), or fall back toos.getcwd()in those contexts. - Symlinks:
Path(__file__).parentis a purely lexical operation and does not follow symlinks, butresolve()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.
Related reading
- Python - How can I make this code asynchronous?
- Python - How do I write a more efficient, Pythonic reduce?
- python - how to append numpy array to a pandas dataframe
- Python - How to intuit word from abbreviated text using NLP?
- Python - Is a dictionary slow to find frequency of each character?
- Python - json without whitespaces
- Python - machine learning
- python - prefix sum algorithm
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseData 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.