0

I have a program that reads csv files. Sometimes users mistakenly try to pass Excel files into the program and I would like to detect this.

Currently, I get a nasty error and I can't seem to catch it.

A simple example:

from csv import DictReader
with open("an_excel_file_pretending_to_be_a_csv_file.csv", "rb") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)

This produces the following error message.

    for row in reader:
  File "c:\Python27\Lib\csv.py", line 107, in next
    self.fieldnames
  File "c:\Python27\Lib\csv.py", line 90, in fieldnames
    self._fieldnames = self.reader.next()
Error: line contains NULL byte

This is happening when the DictReader tries to read the first line of data.

What I would like to do is to catch this as an exception. Unfortunately, this is not an exception, it just borks out of my code with the error message.

from csv import DictReader
with open("an_excel_file_pretending_to_be_a_csv_file.csv", "rb") as f:
    reader = csv.DictReader(f)
    try:
        for row in reader:
            print(row)
    except Exception:
        print "error"

Nothing is captured, the error still breaks out of my code which is in an infinite loop processing many files.

There is a similar question here: Python CSV error: line contains NULL byte

But I would like to catch the error gracefully in my code. How can I do this?

Community
  • 1
  • 1
Graeme Stuart
  • 5,837
  • 2
  • 26
  • 46
  • Maybe just try-except it? If it throws exception, than there's nothing you can do with it. Might as well move on. Also, check this out: http://stackoverflow.com/a/2985005/4029893 – bad_keypoints Jun 25 '15 at 07:40

2 Answers2

2

You could use a general try-except to capture ALL exceptions (be careful because this may be dangerous, hiding errors in your code).

try:
    # your code that can raise exceptions here
except Exception as e:
    # handle ANY exception
else:
    # this executes if no exception occurred (optional)
Caumons
  • 9,341
  • 14
  • 68
  • 82
0

readline function can be used to detect the type before using the csv.DictReader

with open("file1.csv", "rb") as f:
   print f.readline().split(",")
Thiru
  • 3,293
  • 7
  • 35
  • 52