Why is my function turning some strings into separate characters when sending them to the CSV file?

Asked

Viewed 29 times

-1

I created the function below to save the information of a Json to a CSV. But it saves what is being displayed in the OUTPUT. I need the information to stand next to each other and the words not to be separated...

def create_csv(shop_name, access_token):
    with open('order.csv', 'a', newline='') as file:
        writer = csv.writer(file, delimiter=';')
        orders_list = request_products_shopify(shop_name, access_token)
        for order in orders_list['orders']:
            writer.writerow([order['id'], order['fulfillment_status'], order['cancelled_at'], order['cancel_reason'], order['total_discounts'], order['source_name'], order['total_tax'], order['email'], order['line_items'][0]['sku']])
            if len(order['discount_applications']) > 0:
                writer.writerow(order['discount_applications'][0]['type'])
            else:
                writer.writerow('none')

RESULT

0000000000000;;;;0.00;web;0.00;[email protected];83630.S.EX1977
a;u;t;o;m;a;t;i;c
0000000000000;;;;0.00;web;0.00;[email protected];43320.M.00PT01
n;o;n;e
0000000000000;;;;0.00;web;0.00;[email protected];43383.S.00PT01
n;o;n;e
0000000000000;;;;0.00;web;0.00;[email protected];P3006.M.00PT01
a;u;t;o;m;a;t;i;c
0000000000000;;;;0.00;web;0.00;[email protected];83590.M.EX1968 
a;u;t;o;m;a;t;i;c
0000000000000;fulfilled;;;0.00;web;0.00;[email protected];43355.S.00PT01
n;o;n;e

How do I get the information to the way I need it? I don’t understand what’s going on.

  • 1

    You can put an example of the input to test the function?

  • I can’t... it’s confidential. I’m sorry

  • :) The data does not need to be true, create fictitious values that follow the actual data format. EX: Where you have nome:Juliana Nunes,cpf:65392210006 place nome:Jurema Paliares,cpf:99990001111 and do not need to be all data just a three lines for testing.

  • @hkotsubo Yes the result I would like is an additional field without the ';' between the letters.

  • 1

    @Augustovasques understood I’ll edit it. is that Json is giant.

1 answer

2


The method writerow takes as a parameter an iterable object and prints each element of this iterable as a separate column. How strings are eternal, and when iterating over a string each element is one of its characters, so when passing a string directly to writerow, each character will be considered a column. In order for the entire string to be considered a single column, it must be within an iterable one (for example, in a list). Ex:

import csv, sys
writer = csv.writer(sys.stdout, delimiter=';')
writer.writerow('none') # passa a string diretamente
writer.writerow(['none']) # passa a string dentro de uma lista

This code prints out the following:

n;o;n;e
none

Just one detail: the way you made the code, the word "None" is placed on the bottom line because each call to writerow creates a new record. If that was the intention, then the above solution (putting the text in a list) already resolves.

But if you want "None" to be part of the same record (that is, not to be in a separate row), you must first create the list containing all the columns and only at the end write it in the CSV:

for order in orders_list['orders']:
    # primeiro cria a lista com as colunas
    row = [order['id'], order['fulfillment_status'], order['cancelled_at'], order['cancel_reason'], order['total_discounts'], order['source_name'], order['total_tax'], order['email'], order['line_items'][0]['sku']]
    if len(order['discount_applications']) > 0:
        row.append(order['discount_applications'][0]['type'])
    else:
        row.append('none')

    # só no final escrevo o registro no CSV
    writer.writerow(row)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.