Python CSV模块使用实例

举几个例子来介绍一下,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[,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','Column4': '3'}]

这样就可以直接调用DictWriter.writerows方法来处理了:

import csv

fieldnames = ['Column1','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/

相关文章

在前一篇博客中我们介绍了加侧旋的乒乓球弧圈技术的模拟,本...
在近期conda的版本更新中,有可能会删除路径下的_sysconfigd...
本文主要展示了一些lambda表达式的使用示例,通过这些示例,...
本文通过对比Jax和Numpy计算Normalized Hamming Distance的过...
我们知道GPU加速在可并行化程度比较高的算法中,能够发挥出比...
Numpy这个库在Python编程中非常的常用,不仅在性能上补足了P...