Lesson 3: Context managers, clean-up that always happens
15 min read·14 Oct 2026
Module 10 · Lesson 3 · About 45 minutes · Needs: Module 8 (files withencoding="utf-8",try,except,finally), Module 9 Lessons 1 and 2 (classes, inheritance), Lessons 1 and 2 of this module (yield, the@line)
The situation
Amira's request for this module is "Make sure it never breaks." Saving is where it breaks worst. Your program writes data/loans.csv one line at a time. If it stops half way, through a bug or a closed laptop, the file holds only the lines written so far.
This lesson follows one save of the 40 loans, crashing on purpose before line 22. A plain save loses 20 loans. By the end, a safe save loses none.