Get the working directory and a file’s parent in Python
Distinguish the process working directory from a module’s location, navigate parent paths, and account for symlinks and environments without __file__.
Use Path.cwd() or os.getcwd() for the current working directory. Use Path(path).parent or os.path.dirname(path) for a path's parent. These answer different questions from locating the source file of the current module.
Read the working directory
import os
from pathlib import Path
print(os.getcwd())
print(Path.cwd())
This is the process's current directory at the time of the call. It can differ from its startup directory if code calls os.chdir(). Relative paths are interpreted from this directory, not automatically from the directory containing the script.
Get a path's parent
import os
from pathlib import Path
file_path = "/path/to/file.txt"
print(os.path.dirname(file_path)) # /path/to
print(Path(file_path).parent) # /path/to
print(Path(file_path).parent.parent) # /path
These operations can work lexically without proving that the path exists. Path("a/b.txt").parent is Path("a"); for a simple filename, pathlib returns Path("."), while os.path.dirname("b.txt") returns an empty string.
Locate a module on disk
In an ordinary file-backed Python module:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
config_path = BASE_DIR / "settings.json"
resolve() makes the path absolute and follows symlinks. If you need the directory of a symlink used to invoke a script rather than its resolved target, choose a different path policy. __file__ is not guaranteed for every execution environment or module type.
For data shipped inside an installed package, importlib.resources is often more appropriate than assuming every resource is an ordinary adjacent disk file. A package may be loaded from a zip archive or another supported loader.
FAQ
Should I make a relative path absolute first? Do so when you need an absolute location. os.path.abspath() anchors it to the current working directory; Path.resolve() also resolves symlinks and removes .. components. Pick the semantics you intend rather than treating the methods as identical.
Which path interface should I use? pathlib offers readable object operations such as Path("/a") / "b" / "c.txt". os.path remains useful in existing string-based code. Both require attention to the operating system's path conventions.
What about a notebook with no file? Path.cwd() gives the kernel's working directory. It does not necessarily reveal the notebook document's saved location. Supply a project/data path explicitly when that distinction matters.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan