CSV模块的使用

CSV模块的使用

1、csv简介

CSV (Comma Separated Values),即逗号分隔值(也称字符分隔值,因为分隔符可以不是逗号),是一种常用的文本

格式,用以存储表格数据,包括数字或者字符。很多程序在处理数据时都会碰到csv这种格式的文件,它的使用是比

较广泛的(Kaggle上一些题目提供的数据就是csv格式),csv虽然使用广泛,但却没有通用的标准,所以在处理csv

格式时常常会碰到麻烦,幸好python内置了csv模块。下面简单介绍csv模块中最常用的一些函数。

 

更多内容请参考:https://docs.python.org/2/library/csv.html#module-csv

2、csv模块中的函数

  • reader(csvfile, dialect='excel', **fmtparams)
参数说明:
csvfile,必须是支持迭代(Iterator)的对象,可以是文件(file)对象或者列表(list)对象,如果是文件对
象,打开时需要加"b"标志参数。
dialect,编码风格,默认为excel的风格,也就是用逗号(,)分隔,dialect方式也支持自定义,通过调用register_dialect方法来注册,下文会提到。
fmtparam,格式化参数,用来覆盖之前dialect对象指定的编码风格。
    import csv  with open('test.csv','rb') as myFile: lines=csv.reader(myFile) for line in lines: print line 

 

'test.csv'是文件名,‘rb’中的r表示“读”模式,因为是文件对象,所以加‘b’。open()返回了一个文件对象

myFile,reader(myFile)只传入了第一个参数,另外两个参数采用缺省值,即以excel风格读入。reader()返回一个

reader对象lines,lines是一个list,当调用它的方法lines.next()时,会返回一个string。上面程序的效果是将csv

文件中的文本按行打印,每一行的元素都是以逗号分隔符','分隔得来。

 

在我的test.csv文件中,存储的数据如图:

程序输出:

['1', '2'] ['3', 'a'] ['4', 'b']

 

补充:reader对象还提供一些方法:line_num、dialect、next()

  • writer(csvfile, dialect='excel', **fmtparams)

参数的意义同上,这里不赘述,直接上例程:

复制代码
    with open('t.csv','wb') as myFile: myWriter=csv.writer(myFile) myWriter.writerow([7,'g']) myWriter.writerow([8,'h']) myList=[[1,2,3],[4,5,6]] myWriter.writerows(myList) 
复制代码

 

'w'表示写模式。

首先open()函数打开当前路径下的名字为't.csv'的文件,如果不存在这个文件,则创建它,返回myFile文件对象。

csv.writer(myFile)返回writer对象myWriter。

writerow()方法是一行一行写入,writerows方法是一次写入多行。

注意:如果文件't.csv'事先存在,调用writer函数会先清空原文件中的文本,再执行writerow/writerows方法。

补充:除了writerow、writerows,writer对象还提供了其他一些方法:writeheader、dialect

  • register_dialect(name, [dialect, ]**fmtparams)

这个函数是用来自定义dialect的。

参数说明:

name,你所自定义的dialect的名字,比如默认的是'excel',你可以定义成'mydialect'

[dialect, ]**fmtparams,dialect格式参数,有delimiter(分隔符,默认的就是逗号)、quotechar、

quoting等等,可以参考Dialects and Formatting Parameters

    csv.register_dialect('mydialect',delimiter='|', quoting=csv.QUOTE_ALL) 

上面一行程序自定义了一个命名为mydialect的dialect,参数只设置了delimiter和quoting这两个,其他的仍然采用

默认值,其中以'|'为分隔符。接下来我们就可以像使用'excel'一样来使用'mydialect'了。我们来看看效果:

 

在我test.csv中存储如下数据:

以'mydialect'风格打印:

    with open('test.csv','rb') as myFile: lines=csv.reader(myFile,'mydialect') print lines.line_num for line in lines: print line 

输出:

 

['1,2', '3'] ['4,5', '6']

 

 

可以看到,现在是以'|'为分隔符,1和2合成了一个字符串(因为1和2之间的分隔符是逗号,而mydialect风格的分隔

符是'|'),3单独一个字符串。

对于writer()函数,同样可以传入mydialect作为参数,这里不赘述。

  • unregister_dialect(name)

这个函数用于注销自定义的dialect

 

此外,csv模块还提供get_dialect(name)、list_dialects()、field_size_limit([new_limit])等函数,这些都比较

简单,可以自己试试。比如list_dialects()函数会列出当前csv模块里所有的dialect:

    print csv.list_dialects()  

输出:

 

['excel-tab', 'excel', 'mydialect']

 

 

'mydialect'是自定义的,'excel-tab', 'excel'都是自带的dialect,其中'excel-tab'跟'excel'差不多,

只不过以tab为分隔符。

 

csv模块还定义了

一些类:DictReader、DictWriter、Dialect等,DictReader和DictWriter类似于reader和writer。

一些常量:QUOTE_ALL、QUOTE_MINIMAL、.QUOTE_NONNUMERIC等,这些常量可以作为Dialects and Formatting Parameters的值。

 

csv文件格式是一种通用的电子表格和数据库导入导出格式。最近我调用RPC处理服务器数据时,经常需要将数据做个存档便使用了这一方便的格式。

 

 

Python csv模块封装了常用的功能,使用的简单例子如下:

 

复制代码
# 读取csv文件
import csv
with open('some.csv', 'rb') as f: # 采用b的方式处理可以省去很多问题 reader = csv.reader(f) for row in reader: # do something with row, such as row[0],row[1] import csv with open('some.csv', 'wb') as f: # 采用b的方式处理可以省去很多问题 writer = csv.writer(f) writer.writerows(someiterable)
复制代码

 

 

默认的情况下, 读和写使用逗号做分隔符(delimiter),用双引号作为引用符(quotechar),当遇到特殊情况是,可以根据需要手动指定字符, 例如:

 

import csv
with open('passwd', 'rb') as f: reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE) for row in reader: print row

 

 

上述示例指定冒号作为分隔符,并且指定quote方式为不引用。这意味着读的时候都认为内容是不被默认引用符(")包围的。quoting的可选项为: QUOTE_ALL, QUOTE_MINIMAL, QUOTE_NONNUMERIC, QUOTE_NONE.

 

有点需要注意的是,当用writer写数据时, None 会被写成空字符串,浮点类型会被调用 repr() 方法转化成字符串。所以非字符串类型的数据会被 str() 成字符串存储。所以当涉及到unicode字符串时,可以自己手动编码后存储或者使用csv提供的 UnicodeWriter, 具体可参见这里。

 

字典方式地读写

 

csv还提供了一种类似于字典方式的读写,方式如下:

 

格式如下:

 

class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

 

 

其中fieldnames指定字典的key值,如果reader里没有指定那么默认第一行的元素,在writer里一定要指定这个。

 

使用示例

 

复制代码
# 读
>>> import csv
>>> with open('names.csv') as csvfile: ... reader = csv.DictReader(csvfile) ... for row in reader: ... print(row['first_name'], row['last_name']) ... Baked Beans Lovely Spam Wonderful Spam #import csv with open('names.csv', 'w') as csvfile: fieldnames = ['first_name', 'last_name'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
复制代码

 

 

其它

 

csv模块还涉及了其它的概念,比如 Dialects, 还提供了供错误处理的 exception csv.Error 等,因为实际使用较少及就不累赘在此。更多参考官方文档。

 

cr : http://www.cnblogs.com/sjfgod/p/7623395.html

posted on 2017-10-26 16:25 会飞的蝌蚪 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/hfdkd/p/7737483.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390996.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java里面遍历list的方式

问题:Java里面遍历list的方式 对于Java语言有点陌生,我尝试熟悉遍历list(或者其他集合)的所有方法(或者是其他正确的语法)和它们每一个方法的优缺点 给定 List的list对象,我知道有下列方法去循…

python 重启内核_Python从零开始的内核回归

python 重启内核Every beginner in Machine Learning starts by studying what regression means and how the linear regression algorithm works. In fact, the ease of understanding, explainability and the vast effective real-world use cases of linear regression is…

bzoj千题计划282:bzoj4517: [Sdoi2016]排列计数

http://www.lydsy.com/JudgeOnline/problem.php?id4517 组合数错排公式 #include<cstdio> #include<iostream>using namespace std;#define N 1000001const int mod1e97;long long fac[N],inv[N],f[N];void read(int &x) {x0; char cgetchar();while(!isdigit…

chrome启用flash_如何在Google Chrome中启用Adobe Flash Player

chrome启用flashRemember Adobe Flash player? Its that nifty software that lets websites embed videos and web games. Whole websites can even be powered by Flash.还记得Adobe Flash Player吗&#xff1f; 正是这些漂亮的软件使网站可以嵌入视频和网络游戏。 整个网站…

怎么样把Java的字符串转化为字节数组?

问题&#xff1a;怎么样把Java的字符串转化为字节数组 有没有任何方法把Java的字符串转化为字节数组 我尝试这样: System.out.println(response.split("\r\n\r\n")[1]); System.out.println("******"); System.out.println(response.split("\r\n\r\…

Forward团队-爬虫豆瓣top250项目-模块开发过程

项目托管平台地址:https://github.com/xyhcq/top250 开发模块功能: 写入文件功能 开发时间:3小时 实现将爬取到的信息写入到文件中的功能 实现过程&#xff1a; # 打开文件 fopen("top250.txt","w") 在别的队员写的代码基础上&#xff0c;加入功能代码 de…

CSS3 outline-offset 属性 项目中input会遇到

outline在一个声明中设置所有的轮廓属性。outline:颜色&#xff08;outline-line&#xff09;样式&#xff08;outline-style&#xff09;宽度&#xff08;outline-width&#xff09; outline-offset 属性对轮廓进行偏移&#xff0c;并在边框边缘进行绘制。 轮廓在两方面与边框…

回归分析中自变量共线性_具有大特征空间的回归分析中的变量选择

回归分析中自变量共线性介绍 (Introduction) Performing multiple regression analysis from a large set of independent variables can be a challenging task. Identifying the best subset of regressors for a model involves optimizing against things like bias, multi…

winform窗体模板_如何验证角模板驱动的窗体

winform窗体模板介绍 (Introduction) In this article, we will learn about validations in Angular template-driven forms. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will a…

【loj6191】「美团 CodeM 复赛」配对游戏 概率期望dp

题目描述 n次向一个栈中加入0或1中随机1个&#xff0c;如果一次加入0时栈顶元素为1&#xff0c;则将这两个元素弹栈。问最终栈中元素个数的期望是多少。 输入 一行一个正整数 n 。 输出 一行一个实数&#xff0c;表示期望剩下的人数&#xff0c;四舍五入保留三位小数。 样例输入…

查找满足断言的第一个元素

问题&#xff1a;查找满足断言的第一个元素 我刚刚开始使用Java 8的lambdas&#xff0c;我尝试去实现一些我在函数式语言里面经常用的 例如&#xff0c;大部分的函数式语言里有一些查找函数&#xff0c;针对序列或者list进行操作&#xff0c;返回使得断言为真的第一个元素。我…

Lock和synchronized的选择

学习资源:http://www.cnblogs.com/dolphin0520/p/3923167.html 一.java.util.concurrent.locks包下常用的类 1.Lock public interface Lock { void lock();//用来获取锁。如果锁已被其他线程获取&#xff0c;则进行等待。void lockInterruptibly() throws InterruptedException…

python 面试问题_值得阅读的30个Python面试问题

python 面试问题Interview questions are quite tricky to predict. In most cases, even peoples with great programming ability fail to answer some simple questions. Solving the problem with your code is not enough. Often, the interviewer will expect you to hav…

spring boot中 使用http请求

因为项目需求&#xff0c;需要两个系统之间进行通信&#xff0c;经过一番调研&#xff0c;决定使用http请求。服务端没有什么好说的&#xff0c;本来就是使用web 页面进行访问的&#xff0c;所以spring boot启动后&#xff0c;controller层的接口就自动暴露出来了&#xff0c;客…

arduino joy_如何用Joy开发Kubernetes应用

arduino joyLet’s face it: Developing distributed applications is painful.让我们面对现实&#xff1a;开发分布式应用程序很痛苦。 Microservice architectures might be great for decoupling and scalability but they are intimidatingly complex when it comes to de…

怎么样得到平台相关的换行符?

问题&#xff1a;怎么样得到平台相关的换行符&#xff1f; Java里面怎么样得到平台相关的换行符。我不可能到处都用"\n" 回答一 In addition to the line.separator property, if you are using java 1.5 or later and the String.format (or other formatting me…

scrapy常用工具备忘

scrapy常用的命令分为全局和项目两种命令&#xff0c;全局命令就是不需要依靠scrapy项目&#xff0c;可以在全局环境下运行&#xff0c;而项目命令需要在scrapy项目里才能运行。一、全局命令##使用scrapy -h可以看到常用的全局命令 [rootaliyun ~]# scrapy -h Scrapy 1.5.0 - n…

机器学习模型 非线性模型_机器学习:通过预测菲亚特500的价格来观察线性模型的工作原理...

机器学习模型 非线性模型Introduction介绍 In this article, I’d like to speak about linear models by introducing you to a real project that I made. The project that you can find in my Github consists of predicting the prices of fiat 500.在本文中&#xff0c;…

NOIP赛前模拟20171027总结

题目&#xff1a; 1.寿司 给定一个环形的RB串要求经过两两互换后RB分别形成两段连续区域,求最少操作次数(算法时间O(n)) 2.金字塔 给定一个金字塔的侧面图有n层已知每一层的宽度高度均为1要求在图中取出恰好K个互不相交的矩形&#xff08;边缘可以重叠&#xff09;,求最多可以取…

虚幻引擎 js开发游戏_通过编码3游戏学习虚幻引擎4-5小时免费游戏开发视频课程

虚幻引擎 js开发游戏One of the most widely used game engines is Unreal Engine by Epic Games. On the freeCodeCamp.org YouTube channel, weve published a comprehensive course on how to use Unreal Engine with C to develop games.Epic Games的虚幻引擎是使用最广泛的…