Python File Handling
Python File Handling: Context Managers, Modes, and pathlib
Python 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.
File Open Modes at a Glance
| 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 |
Always Specify encoding="utf-8" for Text Files
On 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
")
Common Mistakes to Avoid
- Forgetting
withwhen callingopen(): Unclosed file handles buffer writes in memory and eventually exhaust OS file descriptor limits. - Opening an existing file in
"w"mode accidentally:"w"wipes the entire file immediately on open; use"a"to append or"x"to require a brand-new file. - Hardcoding backslashes in paths: Write
Path("data") / "users.csv"instead of"data\\users.csv".
Frequently Asked Questions
When should I use binary mode ("rb" or "wb")?
Use binary mode for images, PDFs, ZIP archives, or executables. Never pass encoding= when opening a file in binary mode.
Does 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.
How do I check if a file exists before opening it?
Call path.is_file() from pathlib.Path, or wrap open() in try ... except FileNotFoundError:.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.