Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 336
Charles Holbrow Avatar asked Apr 11 '11 20:04

Charles Holbrow


People also ask

What is a good way to handle exceptions when trying to write a file in Python?

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.

How do you handle file exceptions?

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.

What are the types of exceptions and how will you handle it in Python?

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.


2 Answers

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 
like image 54
Tim Pietzcker Avatar answered Nov 15 '22 18:11

Tim Pietzcker


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" 
like image 40
edW Avatar answered Nov 15 '22 18:11

edW