Two files, one with statement
The parenthesised form needs Python 3.10 or later. Without the brackets it also works, on one long line.
A with statement sets something up, runs your block, and then always cleans up, even if the block fails. Files, locks, database connections and temporary settings all use it, and any class with __enter__ and __exit__ can join in.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 7 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a program that writes three lines to todo.txt with a with statement, then reads them back in a second with and prints the number of lines.
Write a class Counter whose __enter__ sets self.count = 0 and returns self, and whose __exit__ prints the word count: and the value of count. Use it in a with ... as c block that adds 1 to c.count three times.
Create src.txt with two lines of text (use a with to write it). Then copy it to dst.txt in upper case using one with statement that opens both files.
Explain it without notes
What exactly happens when Python executes a with statement?
Why is with open(...) safer than calling open and close by hand?
What does it mean if __exit__ returns True? Is that a good idea?
In what order are several context managers in one with entered and exited?
Expected output
ALPHA
BETA
True True