2015-12-21 65 views
0

對於CSV代碼閱讀器使用此example,如何輸出特定列和/或不同順序到CSV?從字典中,如何將特定列輸出爲CSV

import csv 
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume'] 
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007', 
      'Time':'9:36am', 'Change':-0.18, 'Volume':181800}, 
     {'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007', 
      'Time':'9:36am', 'Change':-0.15, 'Volume': 195500}, 
     {'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007', 
      'Time':'9:36am', 'Change':-0.46, 'Volume': 935000}, 
     ] 

with open('stocks.csv','w') as f: 
    f_csv = csv.DictWriter(f, headers) 
    f_csv.writeheader() 
    f_csv.writerows(rows) 

我怎樣才能輸出音量,然後日期(列重新排序,2列沒有輸出)?

回答

2

使用extrasaction參數爲DictWriter constructor

with open('stocks.csv','w') as f: 
    f_csv = csv.DictWriter(f, ['Volume','Date'], extrasaction='ignore') 
    f_csv.writeheader() 
    f_csv.writerows(rows) 

結果:

Volume,Date 
181800,6/11/2007 
195500,6/11/2007 
935000,6/11/2007 
+0

哇,我已經使用了'DictWriter',並且從未知道過t他 - 我通常只是在我將它傳遞給「編輯者」之前做一個詞典理解的生成器。做得好! – wpercy

-1

我不是超級熟悉dictwriter但你可以建立一個字典列表,與您希望的領域

myfields = ['Volume', 'Date'] 
myrows = [] 
for row in rows: 
    myrow = {} 
    for field in myfields: 
     myrow[field] = row.get(field) 
    myrows.append(myrow) 
f_csv = csv.DictWriter(f, myfields) 
f_csv.writeheader() 
f_csv.writerows(myrows) 
+0

Rob的答案更清晰,更好地利用了dictwriter的內置功能。我的回答太慢了! – superbeck