gpt4 book ai didi

python - 在 CSV 文件 python 中添加带逗号的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 16:36:55 33 4
gpt4 key购买 nike

我正在尝试创建一个 CSV 文件,其中包含 Django 模型中的所有对象。该模型包含一个价格字段,我希望在 CSV 中显示为 1,500,但在将数据写入 CSV 时它设置为 1500。

这是我的代码:

import csv
from django.utils.encoding import smart_str
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=Finance Report %s to %s.csv'%(from_date, to_date)
writer = csv.writer(response, csv.excel)
response.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)
writer.writerow([key.replace('_', ' ').title() for key in vars(queryset[0]).keys()])
for obj in queryset:
writer.writerow([str(key) for key in vars(obj).values()])

return response

我应该如何在响应 csv 中添加逗号分隔的金额字段。

最佳答案

在 python 2.7 中,您可以使用它将整数格式化为其中包含逗号的字符串:

'{:,}'.format(1500)

您只需弄清楚哪个字段是价格字段,以便您可以将上面的代码应用于它。

请阅读python doc about format .

关于python - 在 CSV 文件 python 中添加带逗号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124483/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com