Page 150 -
P. 150
close files
Files are left open after an exception!
When all you ever do is read data from files, getting an IOError is annoying,
but rarely dangerous, because your data is still in your file, even though you
might be having trouble getting at it.
It’s a different story when writing data to files: if you need to handle an
IOError before a file is closed, your written data might become corrupted
and there’s no way of telling until after it has happened.
try: Ok.
man_file = open('man_data.txt', 'w') OK
other_file = open('other_data.txt', 'w') OK
print(man, file=man_file) OK
print(other, file=other_file) Not OK!!
Crash!
man_file.close() These two lines of code
DON’T get to run.
other_file.close()
except IOError: OK
print('File error.') OK
Your exception-handling code is doing its job, but you now have a situation
where your data could potentially be corrupted, which can’t be good.
What’s needed here is something that lets you run some code regardless of
whether an IOError has occured. In the context of your code, you’ll want
to make sure the files are closed no matter what.
114 Chapter 4