Use this when handling file paths in Python.
pathlib
pathlib handles file paths as objects in Python, such as Path('logs') / 'run.txt', with methods like exists(), glob() and read_text(), working the same on Windows and Linux.
1. pathlib handles paths cross-platform.
2. Use / operator to join.
3. resolve() and check containment for safety.
4. read_text/write_text.
5. Avoid string path manipulation.
path objects → file operations
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
The negative fixture should deliberately exercise risks such as environment drift, implicit coercion, broad exception handling, blocking/async confusion, shell quoting/subprocess risks, partial writes and non-deterministic external APIs, choosing the cases most relevant to Path object semantics, absolute/relative resolution, symlinks, atomic-safe filesystem operations and platform path differences.
Step 2 Example Narrow the fault
from pathlib import Path
out = Path("backups") / f"{host}.cfg"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(config)
Step 3 Common mistakes Narrow the fault
- Building paths with string concatenation and
/. - Relative paths that depend on the current directory of cron.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- Path objects handle paths cross-platform.
- Use / to join paths.
- Methods: exists(), glob(), read_text().
python3 -c 'from pathlib import Path; print(Path(".").resolve())'— resolve paths- Path.glob / rglob usage — file discovery
- Path traversal checks — safety
ReferenceWhy it matters1 section · depth on demand
What it is
pathlib handles file paths as objects, portable across Linux and Windows.
ReferenceImportant terms & boundaries2 sections · depth on demand
In depth
pathlib handles file paths as objects instead of strings, working the same on Linux, macOS and Windows. It makes file handling in automation shorter and less error-prone.
from pathlib import Path
out = Path("build") / "configs"
out.mkdir(parents=True, exist_ok=True)
for cfg in sorted(Path("templates").glob("*.j2")):
target = out / cfg.with_suffix(".cfg").name
target.write_text(render(cfg), encoding="utf-8")
latest = max(Path("/srv/backups").glob("*.cfg"), key=lambda p: p.stat().st_mtime)
Use Path(__file__).resolve().parent to find files relative to the script, so it works regardless of the current directory — a common reason scripts work interactively but fail from cron.
Mechanics
The linked authority for bounded mechanics is Python Documentation — pathlib; documentation support is separate from observed lab/production Evidence.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Python Automation > pathlib. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://docs.python.org/3/library/pathlib.html · confidence 94%Deep reference
Healthy vs suspicious evidence
Output interpretation
For Path object semantics, absolute/relative resolution, symlinks, atomic-safe filesystem operations and platform path differences, prefer typed fields and stable IDs over human presentation text.