The __exit__ method runs when execution leaves a with block. It lets a context-managed object restore or change state, making cleanup happen at the boundary of the context rather than in separate manual code. section 5.10
File cleanup with with
with open('myfile.txt', 'w') as f: f.write('abc\n') f.write('def\n') When this block ends, the file object's __exit__ method flushes and closes the file. The same protocol can support database transactions, locked sections, and user-defined context-manager classes. section 5.10
