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

Question

Asked By – Charles Holbrow

I want to read a .csv file in python.

  • I don’t know if the file exists.
  • My current solution is below. It feels sloppy to me because the two separate exception tests are awkwardly juxtaposed.

Is there a prettier way to do it?

import csv    
fName = "aFile.csv"

try:
    with open(fName, 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            pass #do stuff here
    
except IOError:
    print "Could not read file:", fName

Now we will see solution for issue: What is a good way to handle exceptions when trying to read a file in python?


Answer

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

This question is answered By – Tim Pietzcker

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0