BeginnerCoder

Lesson 15 — Context managers

with blocks

A context manager runs setup code when a with block starts and cleanup code when it ends — even if an error happens inside. Files are the classic example: the file is closed for you. io.StringIO is an in-memory text file: write() adds text and getvalue() reads it all back.

with open("notes.txt") as f:
    text = f.read()
# f is already closed here

Why it matters: forgetting to close files or release locks causes real bugs, and with makes cleanup automatic.

Want it another way?
Task

Inside the with block, write "hello" into the buffer so the print shows it.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.