听起来csv
对我来说是个问题。
不幸的是,您的问题并不清楚,如果您想修改主文件本身、输出文件或两者兼而有之。这是第二个(它需要一个主文件和一个更新文件,都是 csv 格式,并将未排序的合并内容打印到一个输出文件)。如果这不是您想要的,或者如果您使用逗号分隔数据,但顶部没有字段名,那么根据需要进行更改应该很容易。
import csv
with open("master.csv") as m, open("update.csv") as u, open("out.csv", "w") as o:
master = { line['ID']: line for line in csv.DictReader(m) }
update = { line['ID']: line for line in csv.DictReader(u) }
master.update(update)
fields = csv.DictReader(open("master.csv")).fieldnames
out = csv.DictWriter(o, fields)
out.writeheader()
out.writerows(master.values())
与 master.csv 一样:
ID,Name,Foo,Bar,Baz,Description
1000001,Name here:1,1001,1,description here
1000002,Name here:2,1002,2,description here
1000003,Name here:3,1003,3,description here
1000004,Name here:4,1004,4,description here
1000005,Name here:5,1005,5,description here
1000006,Name here:6,1006,6,description here
1000007,Name here:7,1007,7,description here
1000008,Name here:8,1008,8,description here
1000009,Name here:9,1009,9,description here
和 update.csv 这样:
ID,Name,Foo,Bar,Baz,Description
1000003,UPDATED Name here:3,1003,3, UPDATED description here
1000010,NEW ITEM Name here:9,1009,9,NEW ITEM description here
它输出到 out.csv:
ID,Name,Foo,Bar,Baz,Description
1000010,NEW ITEM Name here:9,1009,9,NEW ITEM description here ,
1000008,Name here:8,1008,8,description here,
1000009,Name here:9,1009,9,description here,
1000006,Name here:6,1006,6,description here,
1000007,Name here:7,1007,7,description here,
1000004,Name here:4,1004,4,description here,
1000005,Name here:5,1005,5,description here,
1000002,Name here:2,1002,2,description here,
1000003,UPDATED Name here:3,1003,3, UPDATED description here,
1000001,Name here:1,1001,1,description here,
请注意,订单不会保留(如有必要,从问题中不清楚)。但它又快又干净。