Python脚本在比较后将一个csv中的数据附加到另一个csv

问题描述 投票:-1回答:1

我有一个脚本,该脚本比较2个csv文件并将数据输出到新的CSV文件。我正在寻找帮助,以便能够以相同的代码将新输出文件中的数据附加到allhistory文件中。有人建议使用什么?

import csv

with open('allhistory.csv', 'r') as t1, open('filewithnewdata.csv', 'r') as t2:
    fileone = t1.readlines()
    filetwo = t2.readlines()

with open('update.csv', 'w') as outFile:
    for line in filetwo:
        if line not in fileone:
            outFile.write(line)
python csv append
1个回答
0
投票

您可以保留要写入update.csv的行的列表,然后写入fileone的内容,然后进行更新,从而覆盖现有文件。例如:

with open('allhistory.csv', 'r') as t1, open('filewithnewdata.csv', 'r') as t2:
    fileone = t1.readlines()
    filetwo = t2.readlines()

matches = []

with open('update.csv', 'w') as outFile:
    for line in filetwo:
        if line not in fileone:
            matches.append(line)
            outFile.write(line)    

with open('allhistory.csv', 'w') as outFile:
    outFile.write(''.join(fileone) + '\n' + ''.join(matches))

注意,您只是比较文件中的整行,您当前不使用csv将每一行拆分为值。

© www.soinside.com 2019 - 2024. All rights reserved.