Python CSV模块使用实例

yipeiwu_com6年前Python基础

举几个例子来介绍一下,Python 的 CSV模块的使用方法,包括,reader, writer, DictReader, DictWriter.register_dialect

一直非常喜欢python的csv模块,简单易用,经常在项目中使用,现在举几个例子说明一下。

复制代码 代码如下:

reader(csvfile[, dialect='excel'][, fmtparam])

参数表:

csvfile
        需要是支持迭代(Iterator)的对象,并且每次调用next方法的返回值是字符串(string),通常的文件(file)对象,或者列表(list)对象都是适用的,如果是文件对象,打开是需要加"b"标志参数。

dialect
        编码风格,默认为excel方式,也就是逗号(,)分隔,另外csv模块也支持excel-tab风格,也就是制表符(tab)分隔。其它的方式需要自己定义,然后可以调用register_dialect方法来注册,以及list_dialects方法来查询已注册的所有编码风格列表。

fmtparam
        格式化参数,用来覆盖之前dialect对象指定的编码风格。

例子:

复制代码 代码如下:

import csv

reader = csv.reader(file('your.csv', 'rb'))
for line in reader:
    print line
 

writer(csvfile[, dialect='excel'][, fmtparam])


参数表(略: 同reader, 见上)

例子:

复制代码 代码如下:

import csv

writer = csv.writer(file('your.csv', 'wb'))
writer.writerow(['Column1', 'Column2', 'Column3'])
lines = [range(3) for i in range(5)]
for line in lines:
    writer.writerow(line)

DictReader

同reader差不多,都是读取CSV用的,只不过会生成一个字典(dict)类型的返回,而不是迭代类型。

DictWriter

 我主要想说的是DictWriter,我为什么会喜欢使用DictWriter呢,因为普通的writer你需要手工去构建列表,尤其是通过表单提交的时候,而我之前因为一直在zope平台上开发,而zope支持一种高级表单数据模型,也就是可以通过定义表单的时候加入相应的标志来使提交后的表单数据自动的生成一个记录(records)类型,也就是生成一个每项数据都是一个字典的列表。这样,我就可以非常方便的直接把表单数据传给 DictWriter而生成csv,当然这个是在你能保证数据的正确性的前提下。好下面我来简单的说明一下这种zope的高级表单数据类型。

例子:

复制代码 代码如下:

<form action='test_form_action' method=post>
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
            <input type="text" name="rows.Column1:records" value="0" />
            <input type="text" name="rows.Column2:records" value="1" />
            <input type="text" name="rows.Column3:records" value="2" />
            <input type="text" name="rows.Column4:records" value="3" />
    <br />
<input type="submit" value="Submit CSV" />
</form>

表单提交后的结果是:
复制代码 代码如下:

rows = [{'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'},
        {'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'},
        {'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'},
        {'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'},
        {'Column1': '0', 'Column2': '1', 'Column3': '2', 'Column4': '3'}]

这样就可以直接调用DictWriter.writerows方法来处理了:
复制代码 代码如下:

import csv

fieldnames = ['Column1', 'Column2', 'Column3', 'Column4']
dict_writer = csv.DictWriter(file('your.csv', 'wb'), fieldnames=fieldnames)
dict_writer.writerow(fieldnames) # CSV第一行需要自己加入
dict_writer.writerows(rows)  # rows就是表单提交的数据

*注意:这里的csv文件写入需要External Method的支持,因为在zope中由于权限沙箱的问题是不能直接操作csv模块来读写文件系统的。


 
这样用起来是不是非常的方便呢,这里给出生成上面表单的DTML代码:
复制代码 代码如下:

<form action='test_form' method=post>
<dtml-in "range(5)">
    <dtml-in "range(4)">
        <input type="text" name="rows.Column&dtml-sequence-number;:records" value="&dtml-sequence-item;" />
    </dtml-in>
<br />
</dtml-in>
<input type="submit" value="Submit CSV" />
</form>

您可以根据您自己的需要来改写这个表单的生成。

参考文献:
http://docs.python.org/lib/module-csv.html
http://www.python.org/dev/peps/pep-0305/

相关文章

Python统计分析模块statistics用法示例

本文实例讲述了Python统计分析模块statistics用法。分享给大家供大家参考,具体如下: 一 计算平均数函数mean() >>>import statist...

实用自动化运维Python脚本分享

并行发送sh命令 pbsh.py #!/usr/bin/python # -*- coding: UTF-8 -*- import paramiko import sys impor...

django之跨表查询及添加记录的示例代码

创建表 书籍模型: 书籍有书名和出版日期,一本书可能会有多个作者,一个作者也可以写多本书,所以作者和书籍的关系就是多对多的关联关系(many-to-many); 一本书只应该由一个出版商...

浅谈用VSCode写python的正确姿势

浅谈用VSCode写python的正确姿势

最近在学习python,之前一直用notepad++作为编辑器,偶然发现了VScode便被它的颜值吸引。用过之后发现它启动快速,插件丰富,下载安装后几乎不用怎么配置就可以直接使用,而且还...

在Python中操作文件之truncate()方法的使用教程

 truncate()方法截断该文件的大小。如果可选的尺寸参数存在,该文件被截断(最多)的大小。 大小默认为当前位置。当前文件位置不改变。注意,如果一个指定的大小超过了文件的当...