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, 'rb') as f:
reader = csv.reader(f)
for row in reader:
pass #do stuff here
except IOError:
print "Could not read file:", fName
try
might be worth it. This can be done withos.path.exists(file)
andos.access(file, os.R_OK)
respectively. Such check can never be free from a race condition though but vanishing files are seldom a normal circumstance ;) – stefanct Apr 8 '17 at 14:50pathlib
module, which makes this problem a lot easier, and should probably be standard Python practice (especially since it was also backported to 2.7). – Rick supports Monica Jul 3 '17 at 13:56IOError
, it does not catchcsv.Error
due to file not being CSV format whenDialect.strict=True
orError
for any other errors (according to CSV package docs), so an outer try, or just simply checking for file exists, then an inner try for CSV exceptions is probably the right answer. – pink spikyhairman May 28 '20 at 13:41