Sub topic 6
Working directory, home directory, and resolve()
This chapter assumes you can build and take apart Path objects, as covered in the earlier chapters. You should also know the difference between a relative and an absolute path. Here you will learn where a relative path points, how to find the user's home directory, and how to turn a messy path into a clean absolute one.
Relative paths depend on process state
A relative path such as Path("data/input.csv") stores no location of its own. The operating system interprets it against the process's current working directory (CWD) each time you use it. The CWD is a per-process setting, usually the directory you were in when you launched the program.
This is a common source of bugs. A script that works from the project root can fail when started from a scheduler, an IDE, or another directory, because the same relative path now points somewhere else.
Path.cwd() returns the current working directory as an absolute Path:
from pathlib import Path
print(Path.cwd()) # for example /home/ana/project
print(Path.home()) # for example /home/anaBoth are class methods, so you call them on Path itself. Both return absolute paths. They are also concrete operations that ask the operating system, so pure path classes do not offer them.
The working directory can change under you
os.chdir() changes the CWD for the whole process. A relative Path object is not tied to the directory that was current when you created it. Every file system call re-reads the CWD.
import os
import tempfile
from pathlib import Path
rel = Path("data.txt")
with tempfile.TemporaryDirectory() as dir_a, tempfile.TemporaryDirectory() as dir_b:
start = Path.cwd()
try:
os.chdir(dir_a)
rel.write_text("from a\n", encoding="utf-8")
print(rel.exists()) # True
os.chdir(dir_b)
print(rel.exists()) # False: same object, different directory
print(rel.resolve().parent == Path(dir_b).resolve()) # True
finally:
os.chdir(start)The finally block restores the original directory. Without it, an exception would leave the process somewhere unexpected, and on Windows the temporary directory could not be deleted while it is the CWD.
The home directory
Path.home() returns the current user's home directory. It follows the same rules as os.path.expanduser("~"). On POSIX systems it reads the HOME environment variable and falls back to the password database. On Windows it uses USERPROFILE, with fallbacks.
Home is the right base for per-user data:
from pathlib import Path
config_dir = Path.home() / ".config" / "myapp"
print(config_dir) # /home/ana/.config/myappThe tilde is just a character
The shell expands ~, but Python does not. Path("~/notes") is a relative path whose first component is a directory literally named ~:
from pathlib import Path
p = Path("~/notes")
print(p.is_absolute()) # False
print(p.parts) # ('~', 'notes')
print(p.expanduser()) # /home/ana/notesexpanduser() replaces a leading ~ with the home directory. It also handles ~username for other users on POSIX. If the path does not start with a tilde, it returns the path unchanged. If Python cannot determine the home directory, it raises RuntimeError.
A common bug is passing user-supplied text such as ~/data straight to open() or Path.exists(). That text refers to a directory named ~ in the CWD, which is almost never what the user meant. Call expanduser() on any path that comes from a config file, a command-line argument, or user input.
Making a path absolute
Two methods produce absolute paths, and they differ in what else they do.
absolute() prepends the CWD if the path is relative. It does nothing else. It does not remove .. or . segments and does not follow symlinks.
resolve() does the following:
- Makes the path absolute.
- Follows every symbolic link (symlink) in it.
- Removes
.and..segments.
The result is a canonical path, one with a single spelling for each real location.
Seeing the difference
The next example builds a small tree with a symlink, then compares both methods on a path that goes through the link and uses ..:
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp).resolve() # resolve first: /tmp may itself be a symlink on macOS
(base / "real" / "inner").mkdir(parents=True)
(base / "link").symlink_to(base / "real", target_is_directory=True)
messy = base / "link" / "inner" / ".." / "file.txt"
print(messy.absolute().relative_to(base)) # link/inner/../file.txt
print(messy.resolve().relative_to(base)) # real/file.txtresolve() follows link to real, steps into inner, then .. takes it back to real. Because the file file.txt does not exist, this only works in non-strict mode, which is the default. Creating symlinks on Windows needs special privileges or Developer Mode, so this example may raise OSError there.
| Method | Prepends CWD | Collapses `..` | Follows symlinks | Needs the path to exist |
|---|---|---|---|---|
| `absolute()` | Yes | No | No | No |
| `resolve()` | Yes | Yes | Yes | No, unless `strict=True` |
| `expanduser()` | No | No | No | No |
Why resolve follows the disk, not the text
You may know os.path.normpath(), which also collapses ... It works purely on the text: a/b/.. becomes a. That is wrong when b is a symlink, because the operating system applies .. to the link's target directory, not to the directory containing the link.
resolve() asks the file system, so it gets the real answer. This is also why it is slower than string manipulation and why it needs the file system to be reachable. The pure path classes have no resolve() for this reason, since they never touch the disk.
strict mode and missing files
By default resolve() does not require the path to exist. Components that exist are resolved, and the remaining components are appended as written. Pass strict=True when a missing path is an error:
from pathlib import Path
target = Path("settings/local.toml")
try:
full = target.resolve(strict=True)
except FileNotFoundError:
print(f"missing: {target.absolute()}")
else:
print(f"using {full}")Strict mode raises FileNotFoundError for a missing component. A symlink loop raises RuntimeError in versions before 3.13 and OSError in 3.13 and later. In 3.13 and later, non-strict mode raises no exception for a loop.
Strict mode combines the existence check and the resolution into one call. A separate exists() check followed by resolve() leaves a short gap in which the file could disappear. Still, the file can vanish after resolve(strict=True) returns, so handle errors when you later open the file.
Anchoring paths to the script, not the CWD
Data files that ship with a program should be found relative to the program's own location. The __file__ variable holds the path of the current module:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
DATA_FILE = BASE_DIR / "data" / "defaults.json"Calling resolve() matters here. __file__ may be relative or may go through a symlink, depending on how the script was launched. Resolving it gives a stable directory regardless of the CWD. In an interactive session or a notebook __file__ does not exist, so fall back to Path.cwd() there.
Normalizing before comparing
Two different spellings can name the same file. Comparing Path objects with == compares the spelling, so these are unequal:
from pathlib import Path
a = Path("docs/../docs/readme.md")
b = Path("docs/readme.md")
print(a == b) # False
print(a.resolve() == b.resolve()) # TrueWhen both files exist, a.samefile(b) is another option. It compares the underlying file identity and so also detects hard links. Use resolve() on both sides before you compare paths or check whether one lies inside another with relative_to(). Otherwise .. segments or symlinks can make an unrelated path look like it is inside a directory.
Putting the steps together
Input from users typically goes through the same sequence: expand the tilde, anchor relative paths to a base you choose, then resolve.
As a function:
from pathlib import Path
def normalize(raw: str, base: Path) -> Path:
path = Path(raw).expanduser()
if not path.is_absolute():
path = base / path
return path.resolve()
print(normalize("~/notes/../todo.txt", Path.cwd()))
print(normalize("out/report.csv", Path("/srv/app"))) # /srv/app/out/report.csvThe second call assumes a POSIX system. The is_absolute() check is optional, since base / path already discards base when path is absolute. Keeping the branch makes the intent explicit.
Common mistakes
- Treating
Path("~")as the home directory. UsePath.home()orexpanduser(). - Assuming the CWD is the script's directory. Anchor with
Path(__file__).resolve().parent. - Calling
resolve()and expecting the file to be checked. Non-strict mode accepts missing paths. Usestrict=Trueorexists(). - Comparing unresolved paths with
==and getting false negatives. - Calling
os.chdir()to make relative paths work, then forgetting to change back. - Resolving paths on one machine and storing them for another. Canonical paths embed machine-specific symlink targets. Store relative paths in portable data.
Exercise
A script contains Path("~/reports").mkdir(exist_ok=True). It runs without error, yet the user cannot find the new directory in their home folder. Where was it created, and how do you fix it?
Show answer
Python does not expand ~, so Path("~/reports") is a relative path whose first component is a directory named ~. mkdir raised no error and created reports inside that path; if ~ did not exist, the call would fail with FileNotFoundError, so a ~ directory must already have existed in the CWD. Either way, the directory is under the CWD, not under home. The fix is Path("~/reports").expanduser().mkdir(exist_ok=True), or (Path.home() / "reports").mkdir(exist_ok=True).
Exercise
Given a symlink link pointing to /data/real, what do Path("link/../x.txt").absolute() and Path("link/../x.txt").resolve() return when the CWD is /work?
Show answer
absolute() returns /work/link/../x.txt, because it only prepends the CWD. resolve() follows the link to /data/real, applies .. to that directory, and returns /data/x.txt.