1 回答

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
你看過(guò)嗎csv-diff
?他們的網(wǎng)站有一個(gè)可能合適的示例:
from csv_diff import load_csv, compare
diff = compare(
? ? load_csv(open("one.csv"), key="id"),
? ? load_csv(open("two.csv"), key="id")
)
這應(yīng)該返回一個(gè)dict對(duì)象,您可以將其解析為 CSV 文件。要將字典解析為行,這是一個(gè)示例。注意:正確編寫(xiě)更改很困難,但這更多的是概念驗(yàn)證 - 根據(jù)您的意愿進(jìn)行修改
from csv_diff import load_csv, compare
from csv import DictWriter
# Get all the row headers across all the changes
headers = set({'change type'})
for key, vals in diff.items():
? ? for val in vals: # Multiple of the same difference 'type'
? ? ? ? headers = headers.union(set(val.keys()))
# Write changes to file
with open('changes.csv', 'w', encoding='utf-8') as fh:
? ? w = DictWriter(fh, headers)
? ? w.writeheader()
? ? for key, changes in diff.items():
? ? ? ? for val in changes: # Add each instance of this type of change
? ? ? ? ? ? val.update({'change type': key}) # Add 'change type' data
? ? ? ? ? ? w.writerow(val)
對(duì)于文件one.csv:
id,? ? ?name, age
?1,? ? ?Cleo,? ?4
?2, Pancakes,? ?2
和two.csv:
id,? ?name, age
?1,? ?Cleo,? ?5
?3, Bailey,? ?1
4,? Elliot,? 10
運(yùn)行此命令會(huì)產(chǎn)生:
change type,? ? ?name, id,? ? ? ? ? ? ? ?changes, age, key
? ? ? added,? ?Bailey,? 3,? ? ? ? ? ? ? ? ? ? ? ,? ?1,
? ? ? added,? ?Elliot,? 4,? ? ? ? ? ? ? ? ? ? ? ,? 10,
? ? removed, Pancakes,? 2,? ? ? ? ? ? ? ? ? ? ? ,? ?2,
? ? changed,? ? ? ? ?,? ?, "{'age': ['4', '5']}",? ? ,? ?1
因此并不適合所有更改,但對(duì)于添加/刪除的行非常有效。
添加回答
舉報(bào)