python中csv文件的读取问题

在python读取csv格式的文件时,使用csv.reader读取文件对象,出现了line contains NULL byte的错误,如下:

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))
file my.csv, line 1: line contains NULL byte
查阅网上,原因在于csv文件中存在空字符,可用以下代码查证:
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')
一般来说,运行后确实打印出空字符的存在。此时可用文本编辑器打开该csv文件,确保csv文件中不存在空字符,
网上给出的解决代码如下,将空字符替换成空字符串:
fi = open('my.csv', 'rb')
data = fi.read()
fi.close()
fo = open('mynew.csv', 'wb')
fo.write(data.replace('\x00', ''))
fo.close()
还有一法,以utf-16的编码格式打开文件,据说可以解决此问题,代码如下:
f=codecs.open(location,"rb","utf-16")
csvread=csv.reader(f,delimiter='\t')
csvread.next()
for row in csvread:
    print row
如果实在解决不了这个问题,用普通的open("mycsv.csv","rU")方法,读取整个文件,然后逐行使用split(",")方法把字符提取出来也是可以的。条条大路通罗马,怎么走,端看个人选择了。
 
posted @ 2017-08-24 18:45  景木  阅读(3039)  评论(0编辑  收藏  举报