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?
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)
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(",")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.