python 處理文件

    

Python CSV文件處理/讀寫

CSV全稱爲“Comma Separated Values”,是一種格式化的文件,由行和列組成,分隔符可以根據需要來變化。 

 

參考文獻:

http://docs.python.org/lib/module-csv.html

http://www.python.org/dev/peps/pep-0305/


reader(csvfile[, dialect='excel'][, fmtparam])

writer(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

file_csv = file('input_csv.csv','wb')

writer = csv.writer(file_csv)
writer.writerow(['Column1', 'Column2', 'Column3'])
writer.writerow(['A', 'B', 'C'])
file_csv.close()

import csv

reader = csv.reader(file('your.csv', 'rb'))
for line in reader:
    print 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模塊來讀寫文件系統的。

 

Python讀寫文件
1.open

使用open打開文件後一定要記得調用文件對象的close()方法。比如可以用try/finally語句來確保最後能關閉文件。

不能把open語句放在try塊裏,因爲當打開文件出現異常時,文件對象file_object無法執行close()方法。

file_object = open('input_csv.csv')
try:
     all_text = file_object.read( )
     print all_text
finally:
     file_object.close( )

2.讀文件
讀文本文件
input = open('data', 'r')
#第二個參數默認爲r
input = open('data')

讀二進制文件
input = open('data', 'rb')

讀固定字節

file_object = open('input_csv.csv', 'rb')
try:
    while True:
         chunk = file_object.read(100)
        if not chunk:
            break
         do_something_with(chunk)
finally:
     file_object.close( )
 

讀每行

list_of_all_the_lines = file_object.readlines( )

如果文件是文本文件,還可以直接遍歷文件對象獲取每行:

for line in file_object:
     process line
 

3.寫文件
寫文本文件
output = open('data', 'w')
 

寫二進制文件
output = open('data', 'wb')
 

追加寫文件
output = open('data', 'w+')
 

寫數據
file_object = open('input_csv', 'w')
file_object.write(all_the_text)
file_object.close( )
 

寫入多行
file_object.writelines(list_of_text_strings)

注意,調用writelines寫入多行在性能上會比使用




 



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