附加到Python中的csv文件

Har*_*rry 0 python

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

agf*_*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)
Run Code Online (Sandbox Code Playgroud)