What is a good way to handle exceptions when trying to read a file in python?

What is a good way to handle exceptions when trying to read a file in python?

How about this:

try:
    f = open(fname, rb)
except OSError:
    print Could not open/read file:, fname
    sys.exit()

with f:
    reader = csv.reader(f)
    for row in reader:
        pass #do stuff here

Here is a read/write example. The with statements insure the close() statement will be called by the file object regardless of whether an exception is thrown. http://effbot.org/zone/python-with-statement.htm

import sys

fIn = symbolsIn.csv
fOut = symbolsOut.csv

try:
   with open(fIn, r) as f:
      file_content = f.read()
      print read file  + fIn
   if not file_content:
      print no data in file  + fIn
      file_content = name,phone,addressn
   with open(fOut, w) as dest:
      dest.write(file_content)
      print wrote file  + fOut
except IOError as e:
   print I/O error({0}): {1}.format(e.errno, e.strerror)
except: #handle other exceptions such as attribute errors
   print Unexpected error:, sys.exc_info()[0]
print done

What is a good way to handle exceptions when trying to read a file in python?

How about adding an else clause to the exception and putting the with statement in the else section? Like this:

try:
  f = open(fname, rb)
except FileNotFoundError:
    print(fFile {fname} not found.  Aborting)
    sys.exit(1)
except OSError:
    print(fOS error occurred trying to open {fname})
    sys.exit(1)
except Exception as err:
    print(fUnexpected error opening {fname} is,repr(err))
    sys.exit(1)  # or replace this with raise ?
else:
  with f:
    reader = csv.reader(f)
    for row in reader:
        pass #do stuff here

Instead of sys.exit(), you could put raise and escalate the error up the chain. It might be better to get system info about the error from the top level error handler.

Leave a Reply

Your email address will not be published. Required fields are marked *