CoursePython from Scratch to Intermediate · Module 10: Intermediate Python · part 69 of 75
Part 69 · Module 10: Intermediate Python

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 with encoding="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.

loans.csv 40 loans save crash before line 22 loans.csv 20 loans left the plain save wrote 20 loans, then stopped
A plain save that crashes before line 22 turns a good file of 40 loans (green) into one with 20 (red: lost data); this lesson's safe save prevents it.

The rest of this part opens with an account

Signing up is free and takes one email. Nothing to pay, and nothing renews.