Skip to Content
Course content

File Handling & Exceptions

Real programs read files and survive bad input — here is how to do both cleanly.

Key topics

  • The with open(...) as f pattern; read/write/append modes; text vs binary.
  • Reading line by line, read() vs readlines(); writing and json/csv module basics.
  • Exceptions: try/except/else/finally; catching specific exceptions; raising with raise; custom exception classes.
  • EAFP vs LBYL styles; the exception hierarchy; never bare except:.
  • Path handling with pathlib.

Exercise / deliverable

Write expenses.py: load a CSV of expenses, skip malformed rows with per-row error messages, compute totals per category, and write a JSON summary — then handle a missing file gracefully.

Level: Beginner | Duration: ~0.5h. Reading and writing files safely, and handling errors with try/except instead of crashing.
Rating
0 0

There are no comments for now.