簡體   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