python csv文件打开错误:_csv.Error: line contains NULL byte

正常的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
from __future__ import division
import csv
import codecs
import xlwt
import pandas as pd
# twsfilename = "mem.csv"#134列
twsfilename = "tws.csv"#123列

#读取行
print u'################获取某一行'
with codecs.open(twsfilename, 'rb', "utf-16") as csvfile:
    reader = csv.reader(csvfile)
    column1 = [row for row in reader]
    print column1[1][0].split("    ")
    print type(column1[1][0].split("    "))

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:",max(column1)
    s = 0
    for i in column1:
        x = float(i)
        s += x
    print "sum:",s,"count:",len(column1)
    # round (s / len(column1), 3)
    print "avg",round (s / len(column1), 3)

 

 

 

最后感谢大神  参考了很多都搞不定 什么.replace('\0','')啊 另存啊 都搞不定  给你几百个这种csv你难道一个个另存啊!

获取list后怎么存成svs 看这个 http://www.cnblogs.com/hanxing/p/6905094.html

 

posted on 2017-05-25 22:24  寒星12345678999  阅读(2826)  评论(0编辑  收藏  举报