我有两个csv文件。每个文件的第一行是标题,其余行是数据。
第一个文件:
a, b, c, d, e, z,
1, 2, 3, 4, 5, 6,
第二档:
a, b, c, f, g,
7, 8, 9,10,11,
我希望合并后的csv如下:
a, b, c, d, e, f, g, z,
1, 2, 3, 4, 5, , , 6,
7, 8, 9, , ,10,11, ,
感谢任何帮助。 谢谢
答案 0 :(得分:-1)
使用csv.DictReader
,csv.DictWriter
:
import csv
import itertools
with open('1.csv') as f1, open('2.csv') as f2, open('new.csv', 'w') as f3:
reader1 = csv.DictReader(f1, skipinitialspace=True)
reader2 = csv.DictReader(f2, skipinitialspace=True)
fieldnames = sorted(set(reader1.fieldnames) | set(reader2.fieldnames))
# If want empty-name column to be placed at the end,
# uncomment following statement.
# Otherwise it will be place at the beginning.
#fieldnames.remove(''); fieldnames.append('')
writer = csv.DictWriter(f3, fieldnames)
writer.writeheader()
writer.writerows(itertools.chain(reader1, reader2))
如果您使用的是Python 3.x,请使用newline=''
打开文件。