Python

Lesson 06

Context managers for files

Use context managers so file handles and other resources close even when work fails.

Good Code

export_reviews.py
def write_review_export(path, rows):
    with open(path, "w", encoding="utf-8") as file:
        for row in rows:
            file.write(f"{row.id},{row.status}\n")

Bad Code

export_reviews.py
def write_review_export(path, rows):
    file = open(path, "w")
    for row in rows:
        file.write(f"{row.id},{row.status}\n")
    file.close()

Review Notes

What to review

Good Code

The good version scopes the file lifetime with with, includes an encoding, and closes the file even if writing a row fails.

Bad Code

The bad version relies on manual close(). An exception in the loop can leave the file open, and the default encoding depends on the environment.

Takeaways

  • Resource lifetime should be visible in the code shape, not hidden in manual cleanup.