繁体   English   中英

附加到 Python 中的 csv 文件

[英]Appending to a csv file in Python

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

csv模块不这样做,您必须将其写入单独的文件,然后用新文件覆盖旧文件,或者将整个文件读入 memory 然后覆盖它。

我推荐第一个选项:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM