随笔 - 366  文章 - 0  评论 - 101  阅读 - 30万

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   寒星12345678999  阅读(2840)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
历史上的今天:
2012-05-25 清空GridView的数据
2012-05-25 从现在的时间加上30天:
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示