【问题标题】:Python script to append data in one csv to another csv after compare比较后将一个 csv 中的数据附加到另一个 csv 的 Python 脚本
【发布时间】:2020-07-21 23:50:18
【问题描述】:

我有一个脚本,它比较 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】:

    您可以保留您写入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 将每一行拆分为值。

    【讨论】:

    • 非常感谢...这可行,但在原始数据和添加的新数据之间有一个空行。中间没有空行吗?
    • 您可以添加strip() 以确保只有一个换行符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多