附加到Python中的csv文件

时间:2011-08-17 16:16:38

标签: python

您好我有一个名称和姓氏的csv文件以及空的用户名和密码列。 如何使用python csv写入每行中的第3列和第4列,只需附加到第3列和第4列,而不是覆盖任何内容。

1 个答案:

答案 0 :(得分: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)
相关问题