Sub topic 14
Common pitfalls and how to avoid them
This chapter assumes you can build paths with /, read their parts, and use exists, read_text, mkdir, and glob. It covers the mistakes that most often cause bugs, and the fix for each.
An absolute segment replaces everything before it
When the right-hand side of / is absolute, pathlib discards the left side.
from pathlib import Path
print(Path("uploads") / "/etc/passwd") # /etc/passwdIf a segment comes from a user, a config file, or a network request, this lets the caller escape your base directory. The segment ../.. has a similar effect. The fix is to resolve the result and confirm it is still inside the base. is_relative_to needs Python 3.9 or later.
from pathlib import Path
def safe_join(base: Path, untrusted: str) -> Path:
base = base.resolve()
target = (base / untrusted).resolve()
if not target.is_relative_to(base):
raise ValueError(f"unsafe path: {untrusted}")
return target
print(safe_join(Path("uploads"), "photos/cat.png"))
try:
safe_join(Path("uploads"), "/etc/passwd")
except ValueError as err:
print(err) # unsafe path: /etc/passwdTreating a Path like a string
A Path is not a str. Concatenating with + raises TypeError, and string methods such as endswith do not exist.
from pathlib import Path
p = Path("data")
# p + "/file.txt" # TypeError
print(p / "file.txt") # data/file.txt
print(str(p / "file.txt").upper()) # DATA/FILE.TXTUse / to build paths. Use str() or os.fspath() only at the edge where an old API wants a string.
Misreading stem and suffix
stem and suffix split at the last dot only. For archive.tar.gz, suffix is .gz and stem is archive.tar. Use suffixes when you need every extension. Also remember that with_suffix replaces only the last one, so Path("archive.tar.gz").with_suffix(".zip") gives archive.tar.zip.
Relative paths depend on the working directory
Path("config.json") points to a different file depending on where the program was started. If you mean "next to this script", anchor the path explicitly.
from pathlib import Path
here = Path(__file__).resolve().parent
config = here / "config.json"Check-then-act races
Calling exists() and then opening the file leaves a gap. Another process can delete or create the file in between.
from pathlib import Path
try:
text = Path("settings.ini").read_text(encoding="utf-8")
except FileNotFoundError:
text = ""Other frequent mistakes
| Mistake | Result | Fix |
|---|---|---|
| `mkdir()` on a nested path | `FileNotFoundError` | `parents=True` |
| `mkdir()` on an existing directory | `FileExistsError` | `exist_ok=True` |
| `read_text()` without `encoding` | Uses the platform default, so results differ between systems | Pass `encoding="utf-8"` |
| Relying on `glob` order | Order varies by file system | Wrap in `sorted()` |
| `Path.rename` onto an existing file | Overwrites on POSIX, fails on Windows | Use `replace()` to get the same behavior everywhere |
| `unlink()` on a directory | `IsADirectoryError` or `PermissionError` | Use `rmdir()` for empty directories |
Two more points are worth knowing. resolve() follows symlinks, so the result may differ from what you typed. rglob on a large tree can be slow, so narrow the pattern or the starting directory when you can.
Exercise
What does Path("reports") / "/tmp/out.csv" produce, and how would you stop a user-supplied name from causing this?
Show answer
It produces /tmp/out.csv, because an absolute right-hand segment discards the left side. Resolve the joined path and check it with isrelativeto against the resolved base directory, and raise an error if the check fails.
Exercise
Why is calling unlink(missing_ok=True) safer than checking exists() first and then calling unlink()?
Show answer
Another process can remove the file between the check and the delete, which makes the second call fail. A single call with missing_ok=True has no gap, so a missing file is not an error.