【问题标题】:Export and Download a list to csv file using Python使用 Python 将列表导出并下载到 csv 文件
【发布时间】:2016-08-16 17:01:40
【问题描述】:

我有一个清单:

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 文件并下载,你能帮帮我吗?

【问题讨论】:

  • 看看 Python CSV 模块。此外,一点点努力就能获得帮助!

标签: python


【解决方案1】:

您可以使用此代码将数据转换为 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()

【讨论】:

  • Tks @grubjesic 为您快速响应,但这些数据“数据”来自“lista.append (rede)”作为“列表”中输入的数据并转换为 csv 文件所以我可以直接下载吗?
  • 我假设这些数据实际上是您的列表。例如rede = {'valor': Decimal('9000.00'), 'mes': 'Julho', 'nome': 'ALFANDEGA 1'} 并使用命令: lista.append(rede) 将其附加到名为 lista 的列表中。我只是在我的示例中调用该列表 (lista) -> 数据。
  • @leonardo santos 你能用你的数据运行我的代码吗?
猜你喜欢
  • 2015-11-12
  • 1970-01-01
  • 2019-11-09
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多