Execute Program
This pattern (set up, do work, clean up) is common across many different problem domains, so Python has a language feature to help with it. Context managers, defined using the with keyword, manage the setup and cleanup processes. Python's file objects support them, as do most database libraries.
Execute Program
By putting the database changes inside of a transaction, we can ensure that we either get all of the records or none of the records. We call that an atomic transaction: it happens completely or not at all.