舉例說明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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章