python csv文件打開錯誤:_csv.Error: line contains NULL byte
阿新 • • 發佈:2017-05-26
sum print question utf-16 null ecs 格式 .cn repl
正常的csv文件讀取如下:
#coding:utf-8 import csv csvfilename = ‘demo.csv‘ print u‘################獲取某一行‘ with open(csvfilename, ‘rb‘) as csvfile: reader = csv.reader(csvfile) rows = [row for row in reader] print rows[0], rows[1], rows[2], rows[3] print u‘################獲取某一列‘ with open(csvfilename,‘rb‘) as csvfile: reader = csv.reader(csvfile) column0 = [row[0] for row in reader] with open(csvfilename, ‘rb‘) as csvfile: reader = csv.reader(csvfile) column1 = [row[2] for row in reader] print column0, column1 s = [1,2,3] for i in column0: print type(i) # print u‘sum:‘,sum(column0)new_column0 = column0.pop(0) print u‘刪除的元素為:‘, new_column0 print u‘刪除後的列表:‘, column0 print type(column0) for i in column0: print type(i)
讀取一個 ucs-2 le 格式(notepa++打開csv)的csv就會報錯: Python CSV error: line contains NULL byte 參考了這個文章裏面的內容
https://stackoverflow.com/questions/4166070/python-csv-error-line-contains-null-byte
代碼如下:
#coding:utf-8 import csv import codecs twsfilename = "tws.csv" #讀取行 print u‘################獲取某一行‘ with codecs.open(twsfilename, ‘rb‘, "utf-16") as csvfile: reader = csv.reader(csvfile) column1 = [row[0] for row in reader] print column1[0] print u‘################獲取某一列‘ with codecs.open(twsfilename, ‘rb‘, "utf-16") as csvfile: reader = csv.reader(csvfile, delimiter=‘\t‘) reader.next()#向下跳一行 這行可以註釋掉 主要為了去掉標題行 column1 = [row[1] for row in reader] print column1 print max(column1)
最後感謝大神 參考了很多都搞不定 什麽.replace(‘\0‘,‘‘)啊 另存啊 都搞不定 給你幾百個這種csv你難道一個個另存啊!
python csv文件打開錯誤:_csv.Error: line contains NULL byte