1

I am trying to create a CSV file I can open with excel from an API data extraction (I don't know how to import it here) by using csvwriter, however for now commas separators are considered a value and added to columns between the actual values.

My code looks like this :

import csv
resources_list="resources_list.csv"

list_keys_res=[]
list_keys_res=list(res['items'][0].keys())

list_items_res=[]
list_items_res=list(res['items'])

resources = open(resources_list, 'w', newline ='')
with resources:
    # identifying header
    writer = csv.writer(resources, delimiter=';')
    header_res = writer.writerow([list_keys_res[1]]+[";"]+[list_keys_res[0]]+[";"]+[list_keys_res[2]]+[";"]+[list_keys_res[4]])
    resource=None
    
    # loop to write the data into each row of the csv file - a row describes 1 resource
    for i in list_items_res:
        resource=list_items_res.index(i)
        list_values_res=[]
        list_values_res=list(list_items_res[resource].values())

        writer.writerow([list_values_res[1]]+[";"]+[list_values_res[0]]+[';']+[list_values_res[2]]+[";"]+[list_values_res[4]])
        i=resource+1`

My goal is to have : name ; id ; userName ; email "Resource 1" ; 1 ; res1 ; myaddress1@host.com "Resource 2" ; 2 ; res2 ; myaddress2@host.com "Resource 3" ; 3 ; res3 ; myaddress3@host.com ...

And for now I have : name;";";id;";";userName;";";email Resource 1;";";1;";"; res1;";"; myaddress1@host.com Resource 2;";";2;";"; res2;";"; myaddress2@host.com Resource 3;";";3;";"; res3;";"; myaddress3@host.com ...

There is the look on Excel for now

The code works just fine I just can't seem to make the form right. Thanks in advance, I hope this will help others aswell!

Peyman.H
  • 1,819
  • 1
  • 16
  • 26
Duperito
  • 11
  • 5
  • csvwriter will add the delimiter automatically to the list items you provide in `writerow()`. Instead of passing `[obj0, ";", obj1, ...]` just pass `[obj0, obj1, ...]` to `writerow()`. – norok2 Nov 16 '22 at 09:37
  • 4
    **You** explicitely add the offending semicolons... Just use `header_res = writer.writerow([list_keys_res[1], list_keys_res[0], list_keys_res[2], list_keys_res[4]])` and same for the values. – Serge Ballesta Nov 16 '22 at 09:37
  • 1
    Ok it works and I feel dumb now ahah, thank you very much to both of you – Duperito Nov 16 '22 at 10:27

0 Answers0