Page 156 -
P. 156
try with
Use with to work with files
Because the use of the try/except/finally pattern is so common when
it comes to working with files, Python includes a statement that abstracts
away some of the details. The with statement, when used with files, can
dramatically reduce the amount of code you have to write, because it negates
the need to include a finally suite to handle the closing of a potentially
opened data file. Take a look:
try: This is the usual “try/
except/finally” pattern.
data = open('its.txt', "w")
print("It's...", file=data)
except IOError as err:
print('File error: ' + str(err))
finally:
if 'data' in locals():
data.close()
try:
with open('its.txt', "w") as data:
print("It's...", file=data)
except IOError as err:
The use of “with” print('File error: ' + str(err))
negates the need for
the “finally” suite.
When you use with, you no longer have to worry about closing any opened
files, as the Python interpreter automatically takes care of this for you. The
with code on the the right is identical in function to that on the left. At Head
First Labs, we know which approach we prefer.
Geek Bits
The with statement takes advantage of a Python technology
called the context management protocol.
120 Chapter 4