Django将字典列表导出到CSV

2024-10-01 04:50:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在中创建了一个词典列表视图.py你说

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},
]

我想把它导出到csv文件。在

^{pr2}$

我知道“对于我的列表中的数据”有一个错误。 “我的”列表包含所有键和值。在

如何只获取我的密钥列表?或者有其他方法将列表导出到csv?在

(我使用django 2和python3.4)


Tags: 文件csv数据py视图列表my错误
1条回答
网友
1楼 · 发布于 2024-10-01 04:50:06

你需要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

相关问题 更多 >