你需要
DictWriter
演示:
import csv
my_list= [
{'user': 1000, 'account1': 100, 'account2': 200, 'account3': 100},
{'user': 1001, 'account1': 110, 'account2': 100, 'account3': 250},
{'user': 1002, 'account1': 220, 'account2': 200, 'account3': 100},
]
with open(filename, "w") as infile:
writer = csv.DictWriter(infile, fieldnames=my_list[0].keys())
writer.writeheader()
for data in my_list:
writer.writerow(data)
with open(filename, 'rb') as infile:
response = HttpResponse(infile, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=mylist.csv'
return response