问题是您需要完整的列集才能在文件开头写入标题。但除此之外,csv.DictWriter 是您所需要的:
# optional: compute the fieldnames:
fieldnames = set()
for d in dict_list:
fieldnames.update(d.keys())
fieldnames = sorted(fieldnames) # sort the fieldnames...
# produce the csv file
with open("file.csv", "w", newline='') as fd:
wr = csv.DictWriter(fd, fieldnames)
wr.writeheader()
wr.writerows(dict_list)
生成的 csv 将如下所示:
A,B,C,D,E
1,2,,,
,,3,4,5
,,6,7,8
如果您真的想将行与不相交的键集组合在一起,您可以这样做:
# produce the csv file
with open("file.csv", "w", newline='') as fd:
wr = csv.DictWriter(fd, sorted(fieldnames))
old = { k: k for k in wr.fieldnames } # use old for the header line
for row in dict_list:
if len(set(old.keys()).intersection(row.keys())) != 0:
wr.writerow(old) # common fields: write old and start a new row
old = row
old.update(row) # disjoint fields: just combine
wr.writerow(old) # do not forget last row
你会得到:
A,B,C,D,E
1,2,3,4,5
,,6,7,8