pathlibPython file handling revolves around the built-in open() function and the with statement (context manager). Wrapping open() inside with guarantees Python closes the file handle automatically even if an exception interrupts your code.
For modern Python 3 projects, pair open() with pathlib.Path instead of string concatenation so file paths work reliably across Windows, macOS, and Linux.
| Mode | Action | Creates File? | Overwrites Existing? |
|---|---|---|---|
"r" |
Read text (default) | No (FileNotFoundError) |
No |
"w" |
Write text | Yes | Yes (truncates to 0 bytes) |
"a" |
Append text at end | Yes | No |
"x" |
Exclusive create | Yes (fails if exists) | No |
"rb" / "wb" |
Read / Write raw bytes | "wb" yes |
"wb" yes |
encoding="utf-8" for Text FilesOn Windows, Python's default text encoding can fall back to cp1252 instead of UTF-8, crashing when reading emojis or international characters. Passing encoding="utf-8" prevents cross-platform encoding bugs.
from pathlib import Path
log_path = Path("logs") / "app.log"
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("a", encoding="utf-8") as handle:
handle.write("2026-11-12 Server started
")
with when calling open(): Unclosed file handles buffer writes in memory and eventually exhaust OS file descriptor limits."w" mode accidentally: "w" wipes the entire file immediately on open; use "a" to append or "x" to require a brand-new file.Path("data") / "users.csv" instead of "data\\users.csv"."rb" or "wb")?Use binary mode for images, PDFs, ZIP archives, or executables. Never pass encoding= when opening a file in binary mode.
Path.read_text() close the file automatically?Yes. Path("notes.txt").read_text(encoding="utf-8") opens, reads, and closes the file in one call, ideal for small config or text files.
Call path.is_file() from pathlib.Path, or wrap open() in try ... except FileNotFoundError:.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.