Python CSV模块使用实例
举几个例子来介绍一下,Python 的 CSV模块的使用方法,包括,reader,writer,DictReader,DictWriter.register_dialect 一直非常喜欢python的csv模块,简单易用,经常在项目中使用,现在举几个例子说明一下。 复制代码 代码如下: reader(csvfile[,dialect='excel'][,fmtparam]) 参数表: csvfile dialect fmtparam 例子: 复制代码 代码如下: import csv reader = csv.reader(file('your.csv','rb')) writer(csvfile[,fmtparam]) 参数表(略: 同reader,见上) 例子: 复制代码 代码如下: import csv writer = csv.writer(file('your.csv','wb')) 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'] *注意:这里的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> 您可以根据您自己的需要来改写这个表单的生成。 参考文献: 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |