我正在使用一些CSV文件,使用以下代码:
reader = csv.reader(open(filepath, "rU"))
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
Run Code Online (Sandbox Code Playgroud)
一个文件抛出此错误:
file my.csv, line 1: line contains NULL byte
Run Code Online (Sandbox Code Playgroud)
我能做什么?谷歌似乎暗示它可能是一个Excel文件被不正当地保存为.csv.有什么方法可以解决Python中的这个问题吗?
==更新==
按照下面@ JohnMachin的评论,我尝试将这些行添加到我的脚本中:
print repr(open(filepath, 'rb').read(200)) # dump 1st 200 bytes of file
data = open(filepath, 'rb').read()
print data.find('\x00')
print data.count('\x00')
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1\x00\x00\x00\x00\x00\x00\x00\x00\ .... <snip>
8
13834
Run Code Online (Sandbox Code Playgroud)
所以该文件确实包含NUL字节.
我正在尝试编写一个查看.CSV文件(input.csv)的程序,并仅重写以某个元素(corrected.csv)开头的行,如文本文件(output.txt)中所列.
这就是我的程序现在的样子:
import csv
lines = []
with open('output.txt','r') as f:
for line in f.readlines():
lines.append(line[:-1])
with open('corrected.csv','w') as correct:
writer = csv.writer(correct, dialect = 'excel')
with open('input.csv', 'r') as mycsv:
reader = csv.reader(mycsv)
for row in reader:
if row[0] not in lines:
writer.writerow(row)
Run Code Online (Sandbox Code Playgroud)
不幸的是,我一直收到这个错误,我不知道它是什么.
Traceback (most recent call last):
File "C:\Python32\Sample Program\csvParser.py", line 12, in <module>
for row in reader:
_csv.Error: line contains NULL byte
Run Code Online (Sandbox Code Playgroud)
相信这里的所有人甚至可以让我达到这一点.