I'm reading 'Core Python Programming 2nd Edition' and came across what I believe is an error in an example. Here is what I sent the author:
380-381 :: 10.3.10 : open() can throw IOError
I have some general comments on this section. You describe two ways of using try-finally-except. The first method was:
try:
try:
ccfile = open('carddata.txt ', 'r')
txns = ccfile.readlines()
except IOError:
log.write('no txns this month\n')
finally:
ccfile.close()
But if open() fails, an IOError will be thrown, and ccfile will be undefined. The code in finally: will attempt to close that undefined variable, and throw a NameError.
The second method was:
try:
try:
ccfile = open('carddata.txt', 'r')
txns = ccfile.readlines()
finally:
ccfile.close()
except:
log.write('no txns this month\n')
But this suffers from the same problem. If open() fails, you attempt to close an undefined variable.
-- EOM
What's the better way to do this?
try:
ccfile = open('carddata.txt', 'r')
except IOError:
log.write('failed to open file\n')
else:
try:
try:
txns = ccfile.readlines()
except IOError:
log.write('no txns this month\n')
finally:
ccfile.close()
Yuck.. anything better? In Python 2.5, you can clean this a bit:
try:
ccfile = open('carddata.txt', 'r')
except IOError:
log.write('failed to open file\n')
else:
try:
txns = ccfile.readlines()
except IOError:
log.write('no txns this month\n')
finally:
ccfile.close()
Still yucky though... The author of the book acknowledged the errata and credited me. He also gives a better solution, setting
ccfile = None
before the block and an
if ccfile:
test before closing.
No Comments/Pingbacks for this post yet...
Donate to keep this site going!
| Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|
| << < | > >> | |||||
| 1 | 2 | 3 | 4 | 5 | ||
| 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 | |||