2011-08-17 75 views
0

嗨,我有一個csv文件,名稱和姓氏以及空的用戶名和密碼列。 如何使用python csv寫入每行的第3列和第4列,只需追加它,不會覆蓋任何內容。在Python中追加csv文件

+3

記住通過單擊選中標記接受問題的答案旁邊的最有用的一個。你只是爲你最近的十個問題之一完成了這一點,其中幾個問題有很好的答案。你應該回去接受最好的! – agf

回答

5

csv模塊沒有這樣做,你必須將它寫出到一個單獨的文件,然後用新的文件覆蓋舊文件,或者將整個文件讀入內存,然後寫上它。

我建議第一個選項:

from csv import writer as csvwriter, reader as cvsreader 
from os import rename # add ', remove' on Windows 

with open(infilename) as infile: 
    csvr = csvreader(infile) 
    with open(outfilename, 'wb') as outfile: 
     csvw = csvwriter(outfile) 
     for row in csvr: 
      # do whatever to get the username/password 
      # for this row here 
      row.append(username) 
      row.append(password) 
      csvw.writerow(row) 
      # or 'csvw.writerow(row + [username, password])' if you want one line 

# only on Windows 
# remove(infilename) 
rename(outfilename, infilename) 
+1

我相信'open(outfilename)'應該是'open(outfilename,'wb')',或者'open(outfilename,'w')' – Marty

+0

謝謝,很好。 'csv'文件使用''wb'',所以我會堅持。 – agf

+0

python 3.2 docs在整個過程中都使用'w',我懷疑它與csv模塊如何處理python 3中的str和bytes有關。 – Marty