Post details: trying to close a file

11/04/06

Permalink 08:57:15 pm, Categories: Python, 259 words   English (US)

trying to close a file

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.

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Leave a comment:

 
 

This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)

You must read and type the 5 chars within 0..9 and A..F, and submit the form.

  

Oh no, I cannot read this. Please, generate a

Viraj's Weblog

Donate to keep this site going!

Amount USD $

June 2011
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      

Search

Categories


Misc

Syndicate this blog XML

What is RSS?

powered by
b2evolution