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, 'r') as f: reader = csv.reader(f) for row in reader: pass #do stuff here except IOError: print "Could not read file:", fName
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
Exception Handling in File Processing. To handle exceptions, we can use the Try, Catch, and Throw keywords. These allowed us to perform normal assignments in a Try section and then handle an exception, if any, in a Catch block.
Example. When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.
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,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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With