Desk Clarity

A field guide to everyday digital problems.

Developer tools / Practical guide

Python Pathlib Treats Tilde as a Folder Name: Expand the Home Path Explicitly

Path("~/file") does not automatically select the current user home directory.

By ON Lab2 min readSources checked November 10, 2026 (KST)

Path constructs a filesystem path; it does not perform shell expansion. Use expanduser for a leading tilde or build from Path.home when the intended anchor is the current user home.

Check the failure with a small fixture

Path("~/file") does not automatically select the current user home directory.

from pathlib import Path
literal = Path("~/reports/example.txt")
assert literal.parts[0] == "~"
expanded = literal.expanduser()
assert expanded == Path.home() / "reports" / "example.txt"
assert Path("reports/~note.txt").expanduser() == Path("reports/~note.txt")
assert Path("$TASK_SAMPLE/file.txt").expanduser() == Path("$TASK_SAMPLE/file.txt")
assert str(literal) != str(expanded)
print("literal, home expansion and environment expansion are distinct")

What the result means

The fixture performs path construction and home lookup without creating or reading files. A tilde at the start follows a user-home convention only after explicit expansion; a tilde inside an ordinary filename remains an ordinary character. Environment variable text is another separate expansion mechanism.

Choose the correction for your caller

Inspect the exact string your program received. A shell may expand an unquoted tilde before Python starts, while a quoted argument, JSON configuration value or string literal can preserve it. Apply expanduser at the configuration boundary where that shorthand is part of your documented format. Path.home is clearer if your own code always means the current user home. Do not replace every tilde in the string, because that changes valid filenames and does not correctly implement named-user expansion.

Limits and the next check

Home lookup can fail when the environment or user database cannot identify a home directory; handle that as configuration failure. Expansion does not create directories, guarantee existence, normalize permissions or confine untrusted paths to a safe directory. resolve addresses a different problem and is not a substitute for home expansion.

Related: Choose a path anchor before reading a data file.

The embedded Python example was executed as an isolated local script on November 10, 2026 (KST), using Python 3.11.6. It demonstrates the stated boundary; it is not a test of your application or a promise of compatibility with every Python release.

Sources & further reading