2014-03-05 81 views
2

我正在寫一個巨大的(160k +)數據從SQL到CSV。我的腳本的功能與預期的完全相同,但我相信必須在輸出中包含標題的更有效方式。我從拼湊下面的writing header in csv python with DictWriter以下,但覺得它缺乏優雅。Python csv:優化標題輸出

這裏是我的代碼:

f = open(outfile,'w') 
wf = csv.DictWriter(f, fieldnames, restval='OOPS') 
wf.writer.writerow(wf.fieldnames) 
f.close() 

f = open(outfile,'a') 
wf = csv.writer(f) 
wf.writerows(rows) 
f.close() 

fieldnames被明確定義(10名自定義列名),rows包含我的查詢fetchall()

回答

2

未經檢驗的,但我不明白爲什麼這不應該做的工作:

import csv 

with open(outfile, "wb") as outf: 
    outcsv = csv.writer(outf) 
    outcsv.writerow(fieldnames) 
    outcsv.writerows(rows)