Page 158 -
P. 158
no finally
You were to grab your pencil and rewrite this try/except/finally
code to use with instead. Here’s your code with the appropriate
finally suite added:
try:
man_file = open('man_data.txt', 'w')
other_file = open('other_data.txt', 'w')
print(man, file=man_file)
print(other, file=other_file)
except IOError as err:
print('File error: ' + str(err))
finally:
if 'man_file' in locals():
man_file.close()
if 'other_file' in locals():
other_file.close()
try:
with open(‘man_data.txt', ‘w') as man_file:
Using two “with”
statements to rewrite print(man, file=man_file)
the code without the
“finally” suite. with open(‘other_data.txt', ‘w') as other_file:
print(other, file=other_file)
except IOError as err:
print(‘File error: ' + str(err))
Or combine the two “open()” calls into one Note the use of the comma.
“with” statement.
with open('man_data.txt', 'w') as man_file, open('other_data.txt’, 'w’) as other_file:
print(man, file=man_file)
print(other, file=other_file)
122 Chapter 4