← Python Crash Course

PCC·10 · Chapter record

Files and Exceptions

Chapter 10 — saving data and handling things going wrong

Done

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.

10.1

Reading from a File

  • 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.
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
Activity 1

Edit the simulated file below to a short 3-line text of your choice, then compare .read() against the line-by-line loop.

Activity 2

Notice the extra whitespace without rstrip() — explain in one sentence why it shows up.

▶ File Reader (simulated pi_digits.txt)