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