Sub topic 14
Common pitfalls and how to avoid them
This chapter collects the mistakes that most often cause bugs in pathlib code. It assumes you can already build paths with /, read their parts, query the file system, and use glob. It also assumes Python 3.9 or newer, because several fixes use is_relative_to(), which was added in 3.9.
Each pitfall below gives the symptom, the cause, and a fix.
Pitfall 1: An absolute segment replaces everything before it
The / operator treats an absolute right-hand side as a new starting point. The earlier segments are discarded without any error.
from pathlib import Path
print(Path("a") / "/etc") # /etc
print(Path("uploads") / "/tmp/x") # /tmp/xThis is harmless with literals. It becomes a security problem when the right-hand side comes from a user, a config file, or an archive entry. A .. segment causes a similar escape, because uploads/../../etc/passwd is still a valid path.
The fix is to resolve the result, then confirm it is still inside the base directory.
from pathlib import Path
def safe_join(base: Path, untrusted: str) -> Path:
base = base.resolve()
candidate = (base / untrusted).resolve()
if not candidate.is_relative_to(base):
raise ValueError(f"path escapes {base}: {untrusted!r}")
return candidate
print(safe_join(Path("uploads"), "photos/cat.jpg"))
for bad in ("/etc/passwd", "../secret.txt"):
try:
safe_join(Path("uploads"), bad)
except ValueError as exc:
print("rejected:", exc)Call resolve() on both the base and the candidate. resolve() collapses .. and follows symlinks, so the comparison tests where the path really points. Comparing only the text would miss both cases.
Pitfall 2: Mixing strings and Path objects
A Path is not a string, so + does not work between the two.
from pathlib import Path
base = Path("data")
try:
print("data/" + Path("x.txt"))
except TypeError as exc:
print(exc) # unsupported operand type(s) for +: 'str' and 'PosixPath'
print(base / "x.txt") # data/x.txtUse / for joining. When an API needs a string, convert at the boundary with str(path) or os.fspath(path). Prefer os.fspath() when the value might already be a string, because it returns strings unchanged and raises TypeError for anything that is not path-like. str() accepts anything and hides mistakes.
Most modern standard library functions (open(), os.listdir(), shutil.copy(), subprocess.run()) accept Path objects directly, so convert only when a call fails.
Pitfall 3: Relative paths depend on the working directory
Path("config.toml") means "in whatever directory the process was started from". Run the script from another folder, from a scheduler, or from an IDE, and the same code finds a different file or none.
from pathlib import Path
HERE = Path(__file__).resolve().parent
CONFIG = HERE / "config.toml"Anchoring on __file__ ties the path to the script's location instead of the caller's. Note that __file__ does not exist in an interactive session or a notebook. There, use Path.cwd() deliberately and say so in a comment.
A related trap is ~. It is not expanded automatically.
from pathlib import Path
literal = Path("~/notes.txt")
print(literal.exists()) # False, looks for a folder named "~"
print(literal.expanduser()) # /home/ana/notes.txtCall expanduser() on any path that may start with ~.
Pitfall 4: Misreading stem, suffix, and with_suffix
suffix and stem split only at the last dot. with_suffix() therefore replaces only the last extension.
from pathlib import Path
p = Path("backup/data.tar.gz")
print(p.with_suffix(".zip")) # backup/data.tar.zip
print(p.with_suffix("")) # backup/data.tarTo replace a compound extension, build the name yourself.
from pathlib import Path
p = Path("backup/data.tar.gz")
new_name = p.name.removesuffix(".tar.gz") + ".zip" # Python 3.9+
print(p.with_name(new_name)) # backup/data.zipThree more behaviors catch people out:
with_suffix("md")raisesValueErrorbecause the suffix must start with a dot.- A dotfile such as
.bashrchas an emptysuffix. Itsstemis the whole name. with_suffix()andwith_name()raiseValueErroron a path with an empty name, such asPath("/").
Pitfall 5: relative_to raises instead of returning None
relative_to() raises ValueError when the path is not under the given base. It also compares parts, not raw text, so /srv/app2 is not under /srv/app.
from pathlib import Path
log = Path("/srv/app2/app.log")
base = Path("/srv/app")
print(log.is_relative_to(base)) # False
try:
log.relative_to(base)
except ValueError as exc:
print("not inside:", exc)Test with is_relative_to() first when you do not know the answer in advance. Do not use str(log).startswith(str(base)), which wrongly accepts /srv/app2.
Pitfall 6: Check-then-act races
A common pattern is to test, then act:
from pathlib import Path
target = Path("cache.json")
if not target.exists():
target.write_text("{}", encoding="utf-8")Between the check and the write, another process can create the file, and you overwrite its content. The answer from exists() is already stale when you receive it. Where the standard library offers an atomic form, use it:
| Instead of | Use |
|---|---|
| `if not d.exists(): d.mkdir()` | `d.mkdir(parents=True, exist_ok=True)` |
| `if f.exists(): f.unlink()` | `f.unlink(missing_ok=True)` (3.8+) |
| `if f.exists(): f.read_text()` | `try: f.read_text() except FileNotFoundError: ...` |
| Create only if absent | `open(path, "x")` raises `FileExistsError` if present |
Also remember that exists() is true for directories. If you need a regular file, call is_file(). mkdir(exist_ok=True) still raises FileExistsError when the existing item is a file, not a directory.
Pitfall 7: Forgetting the encoding
read_text() and write_text() use the platform's default encoding when you pass none. On many Windows setups that is not UTF-8, so a file written on one machine can fail to read on another.
from pathlib import Path
note = Path("note.txt")
note.write_text("café\n", encoding="utf-8")
print(note.read_text(encoding="utf-8"))Always pass encoding= for text. For non-text data, use read_bytes() and write_bytes(). write_text() also replaces the whole file, so use open("a") to append.
Pitfall 8: Surprises in glob and rglob
- Unordered results. The order depends on the file system. Wrap the call in
sorted()when order matters. - One-shot generators.
glob()returns an iterator. A second loop over the same object sees nothing. Storelist(...)if you need it twice. - Mutation while iterating. Creating or deleting files inside the loop can skip or repeat entries. Collect the matches first.
- Depth.
glob("*.py")searches one directory.glob("**/*.py")andrglob("*.py")search the whole tree. - Hidden files. Unlike the older
globmodule,pathlibpatterns do match names starting with a dot. - Matches include directories. A directory named
data.pymatches*.py. Filter withis_file()if you only want files.
from pathlib import Path
files = sorted(p for p in Path("src").rglob("*.py") if p.is_file())
print(len(files), "files")Pitfall 9: rename behaves differently across platforms
Path.rename() replaces an existing destination silently on POSIX but raises FileExistsError on Windows. Path.replace() overwrites on both. Choose the one whose behavior you want, and do not rely on the platform default.
Pitfall 10: Surprising constructor results and platform flavors
An empty path is the current directory, not an error.
from pathlib import Path
print(Path("")) # .
print(Path() == Path(".")) # TrueCode like Path(user_value) / "out" therefore quietly writes into the working directory when user_value is empty. Validate input before wrapping it.
Another flavor trap is parsing a Windows path on Linux. A concrete Path uses the rules of the current system, so backslashes are ordinary characters on POSIX.
from pathlib import Path, PureWindowsPath
s = r"C:\Users\ana\file.txt"
print(Path(s).name) # whole string on POSIX
print(PureWindowsPath(s).name) # file.txtUse PureWindowsPath or PurePosixPath when the path comes from another system, for example a log file or a ZIP entry.
Finally, resolve() on a path that does not exist succeeds by default. It returns a best-effort absolute path. Pass strict=True if a missing file should raise FileNotFoundError.
Quick checklist
- Never join an untrusted segment without
resolve()andis_relative_to(). - Anchor relative paths on
__file__or an explicit base, and callexpanduser()for~. - Prefer atomic options (
exist_ok,missing_ok,try/except) over check-then-act. - Pass
encoding="utf-8"for text. - Wrap
globresults insorted()andlist()as needed.
Exercise
A web handler runs target = Path("/srv/uploads") / filename, where filename comes from the request. A client sends filename = "/etc/passwd". What path does target hold, and how do you make the handler safe?
Show answer
target is /etc/passwd, because an absolute right-hand segment discards the base. Make it safe by resolving both paths and checking containment: base = Path("/srv/uploads").resolve(), target = (base / filename).resolve(), then raise an error if not target.is_relative_to(base). This also blocks ../ escapes and symlinks that point outside the base.
Exercise
What does Path("logs/app.tar.gz").with_suffix(".zip") return, and how would you get logs/app.zip instead?
Show answer
It returns logs/app.tar.zip, because with_suffix replaces only the last extension. To get logs/app.zip, build the name directly: p = Path("logs/app.tar.gz"), then p.with_name(p.name.removesuffix(".tar.gz") + ".zip").