Pythonic way for handling file errors

wink wink at saville.com
Wed Oct 10 14:41:19 EDT 2007


Hello,

I would like to know what would be considered the most
Pythonic way of handling errors when dealing with files,
solutions that seem reasonable using 2.5:

-------
try:
   f = open('afile', 'r')
   content = f.read()
   error = 200
except Exception:
   error = 404
finally:
   if locals().has_key('f'):
       f.close()
------
try:
   f = open('afile', 'r')
   content = f.read()
except Exception:
   error = 404
else:
   error = 200
finally:
   if locals().has_key('f'):
       f.close()
-------
try:
   f = open('afile', 'r')
   content = f.read()
   error = 200
except Exception:
   error = 404
finally:
   try:
       f.close()
   except Exception:
       pass
-------
try:
   f = None
   f = open('afile', 'r')
   content = f.read()
   error = 200
except Exception:
   error = 404
finally:
   if f:
       f.close()
----
try:
   with open('afile', 'r') as f:
       content = f.read()
   error = 200
except Exception:
   error = 404
----

Of the above I think I like the last one best, but I think
I'd really like to have:

with open('afile', 'r') as f with exceptions:
   content = f.read()
   error = 200
except Exception:
   error = 404

Another words from looking at PEP343 it is the author
of the object returned by the with expression that gets
to decide if exceptions are re-raised. But it would seem
to me it should be the programmer using it that should
decide.

Of course as a newbie, I may be way off base.

Thanks,

Wink Saville




More information about the Python-list mailing list