There is a very useful construction in Python for simplifying exception handling when working with contexts such as files or databases. The statement encapsulates the structure try ... finally in one simple command. Here is an example of using with to read a file:
with open('data.txt', 'w') as f: process_file_data(f)
This will try to open the file, run the specified operations on the file (for example, reading), and close the file. If anything goes wrong during the execution of process_file_data, the file is closed properly and then the exception is raised. This is equivalent to:
f = open('data.txt', 'w') try: # some function that does something with the file process_file_data(f) except: ... finally: f.close()
We will use this option in Section 14.1: File handling, when reading and writing files.
The preceding file-reading...