简体   繁体   English

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

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

I have a script which compares 2 csv files and outputs the data to a new CSV file.我有一个脚本,它比较 2 个 csv 文件并将数据输出到一个新的 CSV 文件。 I am looking for help to be able to append the data in the new output file to the allhistory file in thee same code.我正在寻求帮助,以便能够将新 output 文件中的数据 append 转换为相同代码中的 allhistory 文件。 Anyone suggest what to use?有人建议使用什么吗?

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)

You could keep a list of the lines that you write to update.csv and then write the contents of fileone followed by the updates, overwriting the existing file.您可以保留您写入update.csv的行列表,然后写入fileone的内容,然后写入更新,覆盖现有文件。 For example:例如:

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))

Note, you are just comparing whole lines in the file, you are not currently using csv to split each line into values.请注意,您只是比较文件中的整行,您当前没有使用csv将每行拆分为值。

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

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