I want to read a .csv file in python.
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
This question is related to
python
python-2.7
exception
file-io
fname = 'filenotfound.txt'
try:
f = open(fname, 'rb')
except FileNotFoundError:
print("file {} does not exist".format(fname))
file filenotfound.txt does not exist
exception FileNotFoundError Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.
https://docs.python.org/3/library/exceptions.html
This exception does not exist in Python 2.
Adding to @Josh's example;
fName = [FILE TO OPEN]
if os.path.exists(fName):
with open(fName, 'rb') as f:
#add you code to handle the file contents here.
elif IOError:
print "Unable to open file: "+str(fName)
This way you can attempt to open the file, but if it doesn't exist (if it raises an IOError), alert the user!
I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open
, then open
has to be wrapped in a try
. If the call to open
is in the header of a with
, then the with
has to be in a try
to catch the exception. There's no way around that.
So the answer is either: "Tim's way" or "No, you're doing it correctly.".
Previous unhelpful answer to which all the comments refer:
import os
if os.path.exists(fName):
with open(fName, 'rb') as f:
try:
# do stuff
except : # whatever reader errors you care about
# handle error
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,address\n"
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"
Source: Stackoverflow.com