繁体   English   中英

Python 脚本到 append 数据在一个 csv 到另一个 Z628CB5675FF524F3E719BFEAAZE8 比较后

[英]Python script to append data in one csv to another csv after compare

我有一个脚本,它比较 2 个 csv 文件并将数据输出到一个新的 CSV 文件。 我正在寻求帮助,以便能够将新 output 文件中的数据 append 转换为相同代码中的 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)

您可以保留您写入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).strip() + '\n' + ''.join(matches))

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

暂无
暂无

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

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