On this page
article
Tip #29: Use context managers for files and connections
Python tip #29: Use context managers for files and connections.
Tip
Use context managers for files and connections
Why
Following this practice makes your Python code more readable, maintainable, and less error-prone.
Example
# Before (avoid)
# ... less idiomatic approach ...
# After (prefer)
# ... idiomatic Python 3.10+ approach ...