csv 模块为此提供了一个DictWriter类,在另一个 SO answer中对此进行了很好的介绍。关键点是,当您实例化 DictWriter 时,您需要知道所有列标题。您可以从您的 list_of_dicts 构造字段名称列表,如果是这样,您的代码变为
list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
out_file = open(out_path, 'wb')
fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))
writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')
writer.writeheader() # Assumes Python >= 2.7
for row in list_of_dicts:
writer.writerow(row)
out_file.close()
我构建 fieldnames 的方式会扫描整个list_of_dicts
,因此它会随着大小的增加而减慢。相反,您应该fieldnames
直接从数据源构建,例如,如果数据源也是 csv 文件,您可以使用 DictReader 并使用fieldnames = reader.fieldnames
.
您还可以for
用一次调用替换循环writer.writerows(list_of_dicts)
并使用with
块来处理文件关闭,在这种情况下,您的代码将变为
list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))
with open(out_path, 'wb') as out_file:
writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')
writer.writeheader()
writer.writerows(list_of_dicts)