使用Python将列表导出并下载到csv文件

2024-06-16 14:03:31 发布

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

我有一个清单:

lista.append(rede)

打印时,显示:

[{'valor': Decimal('9000.00'), 'mes': 'Julho', 'nome': 'ALFANDEGA 1'}, {'valor': Decimal('12000.00'), 'mes': 'Julho', 'nome': 'AMAZONAS SHOPPING 1'}, {'valor': Decimal('600.00'), 'mes': 'Agosto', 'nome': 'ARARUAMA 1'}, {'valor': Decimal('21600.00'), 'nome': 'Rede Teste Integra\xc3\xa7\xc3\xa3o'}, {'valor': Decimal('3000.00'), 'mes': 'Agosto', 'nome': 'Mercatto Teste 1'}, {'valor': Decimal('5000.00'), 'mes': 'Agosto', 'nome': 'Mercatto Teste 2'}, {'valor': Decimal('8000.00'), 'nome': 'Rede Teste Integra\xc3\xa7\xc3\xa3o 2'}]

我想导出到csv文件并下载,你能帮我吗?你知道吗


Tags: valordecimalappendtesteredenomelistames
1条回答
网友
1楼 · 发布于 2024-06-16 14:03:31

您可以使用以下代码将数据转换为csv:

def Decimal(value):
    #quick and dirty deal with your Decimal thing in the json
    return value

data = [{'valor': Decimal('9000.00'), 'mes': 'Julho', 'nome': 'ALFANDEGA 1'}, {'valor': Decimal('12000.00'), 'mes': 'Julho', 'nome': 'AMAZONAS SHOPPING 1'}, {'valor': Decimal('600.00'), 'mes': 'Agosto', 'nome': 'ARARUAMA 1'}, {'valor': Decimal('21600.00'), 'nome': 'Rede Teste Integra\xc3\xa7\xc3\xa3o'}, {'valor': Decimal('3000.00'), 'mes': 'Agosto', 'nome': 'Mercatto Teste 1'}, {'valor': Decimal('5000.00'), 'mes': 'Agosto', 'nome': 'Mercatto Teste 2'}, {'valor': Decimal('8000.00'), 'nome': 'Rede Teste Integra\xc3\xa7\xc3\xa3o 2'}]

mes = []
nome = []
valor = []
for i in data:
    mes.append(i.get('mes',""))
    nome.append(i.get('nome',""))
    valor.append(i.get('valor',""))

import csv

f = open("file.csv", 'wt')
try:
    writer = csv.writer(f)
    writer.writerow( ('mes', 'nome', 'valor') )
    for i in range(0,len(mes)):
        writer.writerow((mes[i], nome[i], valor[i])) 
finally:
    f.close()

相关问题 更多 >