File Handling and Use of Standard Libraries
File handling and standard libraries concern the boundary between your program and the outside world: reading and writing files, encoding text, and using the library modules that already solve common problems. The exam tests correct resource handling, file modes, and knowing when to reach for a standard module instead of writing your own parser.
Opening files
open(path, mode, encoding=...) returns a file object. Modes: r read, w write (truncates), a append, x exclusive create, plus b for binary and + for read/write. Always use a with block so the file is closed even if an exception is raised. Text mode decodes bytes using the given encoding; specify encoding='utf-8' rather than relying on the platform default.
Reading and writing
read() returns the whole file, readline() one line, readlines() a list of lines. Iterating the file object is the memory-friendly way to process a large file line by line. write() does not add a newline; you supply it. For structured data, prefer json or csv over manual splitting.
Useful standard modules
os and pathlib for paths and directories, json for serialisation, csv for delimited files, math and random for numeric work, datetime for dates, re for pattern matching, and collections for Counter, defaultdict, and deque.
Worked example
import json
with open('data.json', encoding='utf-8') as f:
data = json.load(f)
The with statement guarantees close() on exit, including on error. json.load parses from a file object, while json.loads parses from a string - mixing them up raises a TypeError. If the file is missing, FileNotFoundError propagates, so handle that case explicitly.
Traps
- Using mode
won a file you meant to preserve: it truncates immediately. - Forgetting to close a file, or closing it twice.
- Reading a binary file in text mode.
- Assuming relative paths resolve from the script's directory rather than the current working directory.
- Loading a multi-gigabyte file entirely into memory.