2011-08-17 73 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