我正在使用一些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字节.
当涉及UTF-8/Unicode时,Python中的csv模块无法正常工作.我在Python文档和其他网页上找到了适用于特定情况的片段,但您必须了解您正在处理的编码并使用相应的代码段.
如何从Python 2.6中"正常工作"的.csv文件中读取和写入字符串和Unicode字符串?或者这是Python 2.6的限制,没有简单的解决方案?