简体   繁体   中英

csv.writer writing each character of word

I am trying to export a list of names from the model, Locations. Locations has several objects containing a list of names, for example:

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

The export function is as follows:

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 is iterating on the characters of each name, producing a column of characters rather than names. Instead, I would like each name from each Location object in its own row, in the same column. The above example would result in nine rows.

Any ideas on how to achieve this?

Thank you for any input.

This is because writerows expects a iterable, the rows. Each of these rows has then an iterable of columns. But here export_data is a single iterable. You furthermore do not need to use zip_longest , you can work with:

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

    writer.writerows()

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

or if L_name is a ArrayField , etc. you can unwind it with:

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

    writer.writerows()

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

I ended up doing this:

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`

Converted the list into a string, split the string at the commas then used the line, zip_longest(*str_split, fillvalue='') to output each name vertically on its own row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM