举例说明Python的CSV模块

by Gary Jia上次修改时间: 2007-11-30 17:28
文章标签

举几个例子来介绍一下,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/

引用

引用此文章的链接: http://jiake.org/gary/archive/2007/11/30/python-csv-module/trackback

posted on 2008-12-15 17:29  sislcb  阅读(117377)  评论(6编辑  收藏  举报