res = {}
a=open('a.csv')
for line in a:
(id, rest) = line.split(',', 1)
res[id] = rest
a.close()
b=open('b.csv')
for line in b:
(id, rest) = line.split(',', 1)
res[id] = rest
b.close()
c=open('c.csv', 'w')
for id, rest in res.items():
f.write(id+","+rest)
f.close()
基本上,您使用每一行的第一列作为字典 res 中的键。因为 b.csv 是第二个文件,所以第一个文件 (a.csv) 中已经存在的键将被覆盖。最后在输出文件 c.csv 中再次合并 key 和 rest。
标题行也将取自第二个文件,但我猜这些应该不会有所不同。
编辑:稍微不同的解决方案,合并任意数量的文件并按顺序输出行:
res = {}
files_to_merge = ['a.csv', 'b.csv']
for filename in files_to_merge:
f=open(filename)
for line in f:
(id, rest) = line.split(',', 1)
if rest[-1] != '\n': #last line may be missing a newline
rest = rest + '\n'
res[id] = rest
f.close()
f=open('c.csv', 'w')
f.write("\"id\","+res["\"id\""])
del res["\"id\""]
for id, rest in sorted(res.iteritems()):
f.write(id+","+rest)
f.close()