【问题标题】:csv.writer writing each character of wordcsv.writer 写单词的每个字符
【发布时间】:2021-02-08 04:44:37
【问题描述】:

我正在尝试从模型 Locations 中导出名称列表。 Locations 有几个包含名称列表的对象,例如:

['New York', 'Ohio', California'] ['New York', 'Chicago', California'] ['Miami', 'Ohio', California']

导出函数如下:

def export(request):
    response = HttpResponse(content_type='text/csv')
    writer = csv.writer(response)
    writer.writerow(['Location']) #header

    for launch in Location.objects.all().values_list('L_name'):
       export_data = zip_longest(*launch, fillvalue='')
       writer.writerows(export_data)

response['Content_Disposition'] = 'attatchment';
return response

Writerow 对每个名称的字符进行迭代,生成一列字符而不是名称。相反,我希望每个 Location 对象中的每个名称都在其自己的行中,在同一列中。上面的示例将产生九行。

关于如何实现这一点的任何想法?

感谢您的任何意见。

【问题讨论】:

  • 最简单的答案是:向writer.writerows(...) 提供正确的输入 - 您不会分享您尝试写入的数据的结构/方式或export_data 的外观。它应该是一个列表列表,每个内部列表是一行,它的每个元素都是这一行的一列。没有数据,这很难回答。请editexport_data

标签: python django csv


【解决方案1】:

这是因为writerows 需要一个可迭代的行。这些行中的每一行都有一个可迭代的列。但是这里 export_data 是一个可迭代的。此外,您不需要使用zip_longest,您可以使用:

def export(request):
    response = HttpResponse(content_type='text/csv')
    writer = csv.writer(response)
    writer.writerow(['Location']) #header

    writer.writerows(Location.objects.values_list('L_name'))

    response['Content_Disposition'] = 'attachment';
    return response

或者如果L_nameArrayField 等,您可以通过以下方式展开:

def export(request):
    response = HttpResponse(content_type='text/csv')
    writer = csv.writer(response)
    writer.writerow(['Location']) #header

    writer.writerows((x,) for xs in Location.objects.values_list('L_name')for x in xs)

    response['Content_Disposition'] = 'attachment';
    return response

【讨论】:

  • 感谢您的回复。我已经编辑了我的问题,我希望它更清楚。这会导致 Locations 对象中的每个列表都写入一行,从而生成包含多个元素的三行列表。我希望每个元素都出现在自己的行中。根据我编辑的问题,解决方案将产生九行。
  • @RinaTse:如果你改用writer.writerows((x,) for xs in Location.objects.values_list('L_name')for x in xs) 会怎样?
  • @RinaTse:究竟什么L_nameArrayField
  • 我仍然得到三行,每个单元格中包含三个名称的列表。这行 export_data = zip_longest(*launch, fillvalue='') 似乎至少垂直返回输出,但对于每个字符。
  • L_name 存储了几个 Location 对象,每个对象都是一个名称列表。您的解决方案将每个对象(列表)输出到一行。相反,我试图将每个列表的每个元素放到它自己的一列中。
【解决方案2】:

我最终这样做了:

def export(request):
    response = HttpResponse(content_type='text/csv')
    writer = csv.writer(response)
    writer.writerow(['Base']) #header

    for launch in Location.objects.all().values_list('L_name'):
        list_launch = list(launch)
        full_str = ' '.join([str(elem) for elem in list_launch])
        str_split = ([full_str.split(",")])
        export_data = zip_longest(*str_split, fillvalue='')
        writer.writerows(export_data)

    response['Content_Disposition'] = 'attatchment';
    return response`

将列表转换为字符串,用逗号分割字符串,然后使用行 zip_longest(*str_split, fillvalue='') 将每个名称垂直输出到自己的行中。

【讨论】:

    猜你喜欢
    • 2013-02-14
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2016-03-22
    • 2014-06-19
    • 1970-01-01
    相关资源
    最近更新 更多