What is a good way to handle exceptions when trying to read a file in python? -
i want read .csv file in python.
- i don't know if file exists.
- my current solution below. feels sloppy me because 2 separate exception tests awkwardly juxtaposed.
is there prettier way it?
import csv fname = "afile.csv" try: open(fname, 'rb') f: reader = csv.reader(f) row in reader: pass #do stuff here except ioerror: print "could not read file:", fname
i guess misunderstood being asked. re-re-reading, looks tim's answer want. let me add this, however: if want catch exception open, open has wrapped in try. if call open in header of with, with has in try catch exception. there's no way around that.
so answer either: "tim's way" or "no, you're doing correctly.".
previous unhelpful answer comments refer:
import os if os.path.exists(fname): open(fname, 'rb') f: try: # stuff except : # whatever reader errors care # handle error
Comments
Post a Comment