Sub topic 6
Working directory, home directory, and resolve()
This chapter assumes you can build and take apart Path objects with the / operator and attributes such as name and parent. You should also know the difference between relative and absolute paths. Here you will learn where a relative path points, how to find well-known locations, and how to turn any path into a clean absolute one.
The current working directory
Every running program has a current working directory (CWD). A relative path such as data/input.csv is interpreted from that directory. Path.cwd() returns the CWD as an absolute Path.
from pathlib import Path
here = Path.cwd()
print(here) # for example /home/ana/project
print(here.is_absolute()) # True
relative = Path("data") / "input.csv"
print(relative.is_absolute()) # FalseThe CWD depends on where the program was started, not on where the script file lives. Running python src/app.py from /home/ana/project gives a CWD of /home/ana/project. The same command run from /tmp gives /tmp. This is a common source of "works on my machine" bugs.
The home directory
Path.home() returns the current user's home directory. A path that starts with ~ can be expanded with expanduser().
from pathlib import Path
print(Path.home()) # for example /home/ana
config = Path("~/.config/myapp/settings.toml")
print(config) # ~/.config/myapp/settings.toml
print(config.expanduser()) # /home/ana/.config/myapp/settings.tomlA Path never expands ~ on its own. Path("~/notes") is a relative path whose first segment is literally a directory named ~. Call expanduser() explicitly whenever the text comes from a config file or user input.
Making a path absolute
There are two ways to get an absolute path, and they behave differently.
absolute()puts the CWD in front of a relative path. It does not touch..or.segments and does not follow symbolic links.resolve()makes the path absolute, removes.and..segments, and follows symbolic links (symlinks, which are files that point to other files).
from pathlib import Path
p = Path("data/../data/./input.csv")
print(p.absolute()) # /home/ana/project/data/../data/./input.csv
print(p.resolve()) # /home/ana/project/data/input.csvResolving paths that do not exist yet
By default resolve() does not require the file to exist. This lets you compute where a file will be created. Pass strict=True to raise FileNotFoundError when any part of the path is missing.
from pathlib import Path
target = Path("output/report.txt").resolve()
print(target) # works even if output/ does not exist yet
try:
Path("no_such_dir/file.txt").resolve(strict=True)
except FileNotFoundError:
print("path does not exist")A reliable anchor: the script's own location
To find files that ship next to your script, do not rely on the CWD. Resolve __file__ instead.
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
template = BASE_DIR / "templates" / "page.html"
print(template)__file__ can be relative depending on how Python was started, so calling resolve() first makes the result stable. This code must be saved and run as a script, because __file__ is not defined in an interactive session.
Common mistakes
- Assuming the CWD is the script's folder. Anchor to
Path(__file__).resolve().parentinstead. - Forgetting
expanduser()and creating a directory literally named~. - Using
absolute()and expecting..to disappear. - Using
strict=Truefor a path you are about to create.
Exercise
A script at /srv/app/tools/run.py contains Path("config/app.ini").resolve(). You start it with cd /tmp && python /srv/app/tools/run.py. What path is returned, and how would you change the code so it always points to /srv/app/tools/config/app.ini?
Show answer
It returns /tmp/config/app.ini, because a relative path is resolved against the current working directory (/tmp), not the script's folder. Change it to Path(__file__).resolve().parent / "config" / "app.ini".