2012-07-24 277 views
1

我寫的是,根據用戶供應CSV的行數行爲的簡單功能時保持頭,通過添加或刪除列:Python的CSV:寫入文件

def sanExt(ifpath, ofpath): 
    with open(ifpath, "rb") as fin, open(ofpath, "wb") as fout: 
     csvin = csv.reader(fin) 
     csvout = csv.writer(fout, delimiter=",") 
     fline = csvin.next() 
     if len(fline) == 33: 
      for row in csvin: 
       row.insert(10, "NULL") 
       csvout.writerow(row) 
      print "AG" 
     elif len(fline) == 35: 
      print "AI" 
     elif len(fline) == 36: 
      print "AJ" 
     else: 
      print "Unknown" 

我已經在第一個if聲明停止,只是爲了確保我的代碼工作。在這種情況下,該列已正確添加,但標題已丟失。

如何確保每一行都寫入文件,而不僅僅是[1:len(rows)]

我的方法是完成預期工作的合適pythonic方式嗎?

+1

在報告異常(類型錯誤),回溯總是有益的。否則,告訴我們什麼路線提出異常比你給我們的更好。 – msw 2012-07-24 10:32:47

+0

Quotes the docs:「請注意,與DictReader類不同,DictWriter的fieldnames參數不是可選的,因爲Python的dict對象沒有排序,所以沒有足夠的信息來推斷該行應該寫入csvfile「。並查看http://docs.python.org/library/csv.html#csv.csvreader.fieldnames – msw 2012-07-24 10:38:48

回答

2

如果您不需要csv.DictReader用於通過列名訪問,那麼傳統的解決方案是根據各地類似以下內容:

with open('in.csv') as fin, open('out.csv', 'wb') as fout: 
    csvin = csv.reader(fin) 
    csvout = csv.writer(fout) 
    try: 
     header = next(csvin) 
     csvout.writerow(header) 
    except StopIeration as e: 
     pass # empty file - either handle, or we'll just continue and drop out of loop 

    for row in csvin: 
     csvout.writerow(row) # do some real work here... 
+0

剛剛刪除我的答案,這正是你的建議。我通過試驗和錯誤,而不是代碼福。謝謝。 – CHM 2012-07-24 10:58:09

1

使用csv.DictReader,csv.DictWriter及其writeheader()方法來處理標題行,代碼很少。