问题出现在这个question ,我将在这段代码中概括一下:
import csv
FH = open('data.csv','wb')
line1 = [97,44,98,44,99,10]
line2 = [100,44,101,44,102,10]
for n in line1 + line2:
FH.write(chr(n))
FH.write(chr(0))
FH.close()
import _csv
FH = open('data.csv')
reader = csv.reader(FH)
for line in reader:
if '\0' in line: continue
if not line: continue
try:
print line
except _csv.Error:
print 'error'
运行它:
$ python test.py
['a', 'b', 'c']
['d', 'e', 'f']
Traceback (most recent call last):
File "test.py", line 14, in <module>
for line in reader:
_csv.Error: line contains NULL byte
所以,我猜想在文件中包含 NUL 会导致“无法捕获”的异常。
问题是,除了首先清理文件之外,处理这个问题的最佳方法是什么? “无法捕获”的异常有多常见?
请您参考如下方法:
您没有将“try” block 放在正确的位置来捕获此异常。换句话说,这个异常是“可捕获的”,只需重新访问您引用的问题即可。
回溯清楚地表明问题出在“for”语句这一行。
