Head First Python

Page 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” print(man, file=man_file) statements to rewrite the code without the with open(‘other_data.txt', ‘w') as other_file: “finally” suite.

print(other, file=other_file)

except IOError as err: print(‘File error: ' + str(err)) ls into one Or combine the two “open()” cal “with” statement.

Note the use of the comma.

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


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.