PCC·10 · Chapter record
Files and Exceptions
Chapter 10 — saving data and handling things going wrong
Five sessions on files and errors: reading a file into memory, writing and appending to one, handling exceptions with try/except/else, failing silently on purpose, and saving data with JSON. Since this page runs entirely in your browser, each demo uses a small simulated file rather than your real filesystem — the Python code shown is exactly what you'd write for a real file. Each session explains the concept, lists the key terms, then gives you exercises — try them yourself before revealing the code.
Reading from a File
Concept
with open(filename) as file_object:opens a file — the with block closes it automatically when done, even if something goes wrong inside..read()pulls the entire file into memory as one string; loop directly over the file object (or use.readlines()) to work through it one line at a time.- Every line from a text file carries an invisible trailing newline — chain
.rstrip()to strip it back off when printing.
Key Terms
- open() / with
- opens a file and closes it automatically at the end of the block
- .read()
- reads the whole file into one string
- .readlines()
- reads the file into a list, one entry per line
Exercise
Edit the simulated file below to a short 3-line text of your choice, then compare .read() against the line-by-line loop.
Notice the extra whitespace without rstrip() — explain in one sentence why it shows up.
Writing to a File
Concept
open(filename, 'w')opens (or creates) a file in write mode — but any existing content is erased first..write()doesn't add newlines on its own — include\nyourself if you want each call to land on its own line.open(filename, 'a')opens in append mode instead — new writes are added to the end, and nothing existing is erased.
Key Terms
- 'w' mode
- write mode — creates the file if needed, erases existing content first
- 'a' mode
- append mode — adds new content to the end without erasing
Exercise
Write a line with mode 'w', then write a different line with mode 'w' again — confirm the first one disappeared.
Now use mode 'a' twice in a row and confirm both new lines get added without erasing what came before.
try / except / else
Concept
- Wrap risky code in
try:— Python jumps to a matching except: block instead of crashing with a traceback. else:holds code that should run only if the try block succeeded — it keeps the "what if it works" logic separate from the "what if it fails" logic.- FileNotFoundError is raised when
open()can't find the file you asked for — exactly the kind of thing try/except is built for.
Key Terms
- try / except / else
- attempt code, handle its failure, and run success-only code separately
- FileNotFoundError
- raised when open() can't find the requested file
Exercise
Divide two numbers below. Try dividing by zero, and try typing text instead of a number — read the different message for each.
Try opening a file that doesn't exist in the widget below, then one that does — compare the two outcomes.
Failing Silently
Concept
passin an except block tells Python to do nothing at all — the program moves on as if the error never happened.- Useful when a missing file isn't worth bothering the user about — like skipping a book that isn't there while still reporting word counts for the ones that are.
- It's a judgment call: report errors that matter to your user, and fail silently on the ones that don't.
Key Terms
- pass
- a statement that does nothing — a deliberate no-op
- failing silently
- catching an error and continuing without telling the user
Exercise
Add a filename that doesn't exist in the simulated library below to the list, and confirm it gets skipped with no error message at all.
Storing Data with JSON
Concept
json.dump(data, f)writes a Python list or dictionary into a file as JSON text — simple structures translate over almost exactly as written.json.load(f)reads that JSON text back into a real Python list or dictionary — a clean way to hand data between two runs of a program, or between two different programs entirely.- A common pattern: try to load remembered data, and if the file doesn't exist yet, fall back to asking for it fresh.
Key Terms
- json.dump()
- writes Python data into a file as JSON text
- json.load()
- reads JSON text from a file back into Python data
Exercise
Save a username with json.dump(), then load it back to confirm it survived. Then forget it and try loading again — what would a real program do at that point?