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 what the above code is Doing:
1. It opens the file in binary mode.
2. It creates a csv.reader object.
3. It loops over the rows in the file.
4. It closes the file when the loop terminates.
If any of the lines in the with block raises an exception, the file f will be closed before the exception is caught by an outer exception handler.