在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(",")方法把字符提取出來也是可以的。條條大路通羅馬,怎么走,端看個人選擇了。