Reading and writing files with context managers
Many programs will access external resources such as database connections, network connections, and OS files. It's important for a reliable, well-behaved program to release all external entanglements reliably and cleanly.
A program that raises an exception and eventually crashes can still properly release resources. This includes closing a file and being sure that any buffered data is properly written to the file.
This is particularly important for long-running servers. A web server may open and close many files. If the server did not close each file properly, then data objects might be left in memory, reducing the amount of room that can be used for ongoing web services. The loss of working memory appears like a slow leak. Eventually the server needs to be restarted, reducing availability.
How can we be sure that resources are acquired and released properly? How can we avoid resource leaks?
Getting ready
One common example of expensive and important...