Module 5: Files, Modules, and Objects

Files and Context Managers

Files and Context Managers

Context managers pair resource acquisition with guaranteed cleanup. Text files should use an explicit encoding; binary files should remain bytes; large inputs should usually be streamed.

Module: Module 5: Files, Modules, and Objects

Core mental model

This lesson is built around four connected ideas. Read them as a decision framework, then prove each one with the walkthrough.

  • with closes a file even when processing raises an exception.
  • Text mode works with str and binary mode works with bytes.
  • pathlib provides portable, composable path operations.
  • Parsing should be testable without disk IO.

Walkthrough

from pathlib import Path

source = Path("events.log")
summary = Path("summary.txt")
error_count = 0

with source.open(encoding="utf-8") as stream:
    for line in stream:
        if line.startswith("ERROR"):
            error_count += 1

with summary.open("w", encoding="utf-8") as output:
    output.write(f"errors={error_count}\n")

Iteration streams one line at a time. Each with block owns one resource. Write mode replaces existing content, so output location and overwrite policy must be deliberate.

Hands-on lab

Stream an event file through the normalizer and write accepted records plus a rejection report. Test missing, empty, and multilingual files.

What to watch for

  • read() can create avoidable memory pressure on large files.
  • Platform-default encodings make scripts nonportable.
  • Unvalidated output paths can overwrite unintended files.

Engineering checklist

  • Connect the lesson's mental model to the choices made in the walkthrough.
  • Test the normal case, an empty or boundary case, and one invalid case.
  • Keep external input, side effects, and reusable logic in clearly separated layers.
  • Prefer the clearest correct implementation before optimizing or generalizing it.

Completion check

You can implement the lab without copying the example, explain the core concepts in your own words, and show tests or terminal output that demonstrate the expected and failure paths.