Python CSV模块使用实例_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/

时间: 2024-08-30 10:43:17

Python CSV模块使用实例_python的相关文章

Python httplib模块使用实例_python

httplib模块是一个底层基础模块,实现的功能比较少,正常情况下比较少用到.推荐用urllib, urllib2, httplib2. HTTPConnection 对象 class httplib.HTTPConnection(host[, port[, strict[, timeout[, source_address]]]]) 创建HTTPConnection对象 HTTPConnection.request(method, url[, body[, headers]]) 发送请求 HT

Python json模块使用实例_python

实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接传递,所以需要将其转换成字符串形式.转换的过程也是一种序列化过程. 用json.dumps序列化为json字符串格式 复制代码 代码如下: >>> import json >>> dic {'Connection': ['keep-alive'], 'Host': ['127.0.0.1:5000'], 'Cache-Control': ['max-age=0']} >>>

python uuid模块使用实例_python

uuid是一种唯一标识,在许多领域作为标识用途.python的uuid模块就是用来生成它的. 闲话不说,python提供的生成uuid的方法一共有4种,分别是: 1.从硬件地址和时间生成 2.从md5算法生成 3.随机生成 4.从SHA-1算法生成 他们在uuid模块里对应uuid1, uuid3, uuid4, uuid5这几个方法,注意没有uuid2. 下面是示例: 复制代码 代码如下: #-*- encoding: gb2312 -*- import uuid print uuid.uui

python optparse模块使用实例_python

使用命令行时,如果要添加选项的话,python 2.3里新增加了一个模块叫optparse,也是专门来处理命令行选项的. 复制代码 代码如下: from optparse import OptionParser parser = OptionParser() parser.add_option("-p", "--pdbk", action="store_true",                   dest="pdcl",

Python fileinput模块使用实例

  这篇文章主要介绍了Python fileinput模块使用实例,fileinput模块可以遍历文本文件的所有行,本文就给出它的使用代码实例,需要的朋友可以参考下 fileinput模块可以遍历文本文件的所有行.它的工作方式和readlines很类似,不同点在于,它不是将全部的行读到列表中而是创建了一个xreadlines对象. 下面是fileinput模块中的常用函数 input() #它会返回能够用于for循环遍历的对象. filename() #返回当前文件的名称 lineno() #返

python的re模块应用实例_python

本文实例讲述了python的re模块应用.是非常重要的应用技巧.分享给大家供大家参考. 具体方法如下: import re # match_object = re.match('foo','foo') if match_object is not None: print type(match_object) print match_object.group() # match_object = re.match('foo','fooabv') if match_object is not Non

python使用cPickle模块序列化实例_python

本文实例讲述了python使用cPickle模块序列化的方法,分享给大家供大家参考. 具体方法如下: import cPickle data1 = ['abc',12,23] #几个测试数据 data2 = {1:'aaa',"b":'dad'} data3 = (1,2,4) output_file = open("a.txt",'w') cPickle.dump(data1,output_file) cPickle.dump(data2,output_file)

python中bisect模块用法实例_python

本文实例讲述了python中bisect模块用法,分享给大家供大家参考. 具体方法分析如下: 这个模块只有几个函数,一旦决定使用二分搜索时,立马要想到使用这个模块. 示例代码如下: import bisect L = [1,3,3,6,8,12,15] x = 3 x_insert_point = bisect.bisect_left(L,x)#在L中查找x,x存在时返回x左侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回左侧位置1 print x_insert_point x_

python中pygame模块用法实例_python

本文实例讲述了python中pygame模块用法,分享给大家供大家参考.具体方法如下: import pygame, sys from pygame.locals import * #set up pygame pygame.init() windowSurface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption("hello, world") BLACK = (0, 0, 0) WHITE