Files, I/O & context managers
Reading and writing files, the with statement, pathlib, CSV and JSON.
Reading and writing files
open() is the entry point for file I/O; the mode string decides read/write/append and text/binary behavior.
open(path, mode) returns a file object; mode combines a base action ("r" read, "w" write and truncate, "a" append, "x" create-exclusive) with an optional "b" for binary instead of text. Reading the whole file is .read(), reading line by line is for line in file: or .readlines(), and writing is .write(text). Text mode automatically handles the platform's newline convention and decodes bytes to str using an encoding; if you omit encoding=, Python falls back to a platform/locale-dependent default rather than a fixed UTF-8, so portable code should pass encoding="utf-8" (or whatever encoding the data actually uses) explicitly. Binary mode ("rb"/"wb") works with raw bytes and does no such conversion, which matters for anything that is not plain text, like images.
Key points
- Mode combines an action (r/w/a/x) with an optional b for binary
- "w" truncates an existing file entirely; "a" appends without truncating
- Text mode decodes to str with an encoding; binary mode works with raw bytes
Code
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("second line\n")
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())Writing, then appending, then reading a text file line by line — each open() call scoped by a with block.
Common pitfalls
- Opening with "w" on an existing file silently destroys its previous contents
- Omitting encoding="utf-8" relies on the OS default encoding, which differs between systems and can misdecode non-ASCII text
Practice exercise
Write a script that reads a text file line by line, counts how many lines contain the word "error" (case-insensitive), and writes that count to a summary file.
The with statement and context managers
with guarantees cleanup (like closing a file) happens even if an error occurs inside the block.
with open(path) as f: both opens the file and guarantees it is closed when the block ends, whether it ends normally or because an exception was raised inside it — equivalent to a manual try/finally but far less error-prone to write correctly. This pattern is not limited to files: any object implementing the context manager protocol (__enter__/__exit__) works with with, including database connections, locks, and temporary state changes. Multiple context managers can be opened in one with statement, comma-separated, and all are guaranteed to close correctly even if one of them fails partway through.
Key points
- with guarantees cleanup runs even if the block raises an exception
- Any object with __enter__/__exit__ works with with, not just files
- Multiple context managers can share one with statement, comma-separated
Code
with open("input.txt") as src, open("output.txt", "w") as dst:
for line in src:
dst.write(line.upper())
# both files are guaranteed closed here, even if upper() had failedTwo files opened in one with statement, both guaranteed to close even on failure.
Common pitfalls
- Manually calling f.close() and forgetting it on an early return or exception leaks the file handle
- Code that uses the file object after the with block has exited will find it already closed
Practice exercise
Rewrite a function that opens a file, might raise an exception while processing it, and manually calls close() at the end, to instead use a with statement — and explain why the rewrite is safer.
Filesystem paths with pathlib
Path objects, joined with /, replace error-prone string concatenation for building filesystem paths.
pathlib.Path represents a filesystem path as an object rather than a plain string, and overloads the / operator so Path("data") / "reports" / "q1.csv" builds a correct path on any operating system without manually inserting separators. Common operations live directly on the object: .exists(), .is_file(), .mkdir(parents=True, exist_ok=True), .glob("*.txt") for pattern matching, and .read_text()/.write_text() for simple whole-file text I/O without a separate open() call. pathlib is the modern recommendation over manually joining os.path strings for nearly all new code.
Key points
- The / operator joins path segments correctly on any OS
- .exists(), .is_file(), .mkdir(), .glob() live directly on the Path object
- .read_text()/.write_text() handle simple whole-file text I/O without a separate open()
Code
from pathlib import Path
reports_dir = Path("data") / "reports"
reports_dir.mkdir(parents=True, exist_ok=True)
for csv_file in reports_dir.glob("*.csv"):
print(csv_file.name, csv_file.stat().st_size)Building a nested path, ensuring it exists, and iterating matching files with their sizes.
Common pitfalls
- mkdir() without exist_ok=True raises FileExistsError if the directory is already there
- Mixing pathlib.Path objects with raw os.path string functions in the same codebase adds unnecessary inconsistency
Practice exercise
Write a function that takes a directory path, uses pathlib to find every .txt file recursively, and returns a dict mapping each file's name to its size in bytes.
Working with CSV and JSON data
The standard library's csv and json modules handle the escaping and structure details so you don't hand-roll a parser.
The csv module's csv.reader/csv.writer (and the dict-based csv.DictReader/csv.DictWriter) correctly handle edge cases like commas or quotes embedded inside a field's value, which a naive line.split(",") gets wrong. The json module's json.load(file)/json.dump(obj, file) convert between JSON text and native Python dict/list/str/int/float/bool/None structures directly, and json.loads(text)/json.dumps(obj) do the same for in-memory strings instead of files. Both formats are common enough in real-world data exchange that reaching for the standard library module is almost always correct over hand-parsing.
Key points
- csv.DictReader/DictWriter correctly handle embedded commas and quotes, unlike manual split()
- json.load/dump work with files; json.loads/dumps work with in-memory strings
- JSON maps directly onto dict/list/str/int/float/bool/None, no manual parsing needed
Code
import csv, json
with open("users.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
with open("users.json", "w", encoding="utf-8") as f:
json.dump(rows, f, indent=2)Reading a CSV file into a list of dicts, then dumping that same data as formatted JSON.
Common pitfalls
- Opening a CSV file without newline="" can produce extra blank rows on Windows
- json.dump fails with a TypeError on non-JSON-serializable objects like datetime unless you supply a custom default handler
Practice exercise
Write a script that reads a CSV of products (name, price, quantity), converts price and quantity to numbers, and writes the result as a JSON array of objects.