2.7. Making Python Programs Robust¶
Here is a super cautious, but correct way to open and read a file:
import sys try: file = open('myFile') except IOError: print 'File does not exist.' sys.exit(1) else: print 'File exists.' try: lines = file.readlines() finally: file.close()
elseblock executes only if no exceptions are thrown, while the
finallyblock always executes. The
file.close()statement is in a
finallyblock to ensure that it gets closed, even if an uncaught exception is raised and the program will exit.
Following is the new, cleaner, but just as robust way to express the same
operation in Python. This works because the file object was made to work with
with keyword to ensure that the file is always closed after
being opened. 
try: with open('myFile') as file: lines = file.readlines() except IOError: print 'File does not exist.' sys.exit(1) else: print 'File exists and has been read.'