PereCullera PereCullera - 2 months ago 15
Python Question

Write multiple values in a csv cell without brackets in python

I have a list of objects. Each object have different attributes.
One of which is a list
I would like to export this objects to a csv file that looks like

a, "1,2,3"
b,"1,2,3"


so that the csv is readable in a Excel program

My code looks something like this:

final_list = []
for a in list:
first_value = a.first_value
list2 = []
for b in a.list:
list2.append(b)

final_list.append(first_value)
final_list.append(list2)
with open('file' ) as f:
writer = csv.writer(f)
writer.writerows(final_list)
pass


which results in this csv rows with the brackets and quotes that i don't want

1, "['1','3','4']"
2,"['1','2','3']"


I need 2 values per row:
a
and
1,2,3
as string

Answer

if you do that:

    final_list.append(first_value)
    final_list.append(list2)

you create a row with a value and a list.

The csv module performs a str conversion when writing, which explains you see the string as it is printed when you debug in python.

Instead do:

    final_list.append(a.first_value)  # string
    final_list.append(",".join(a.list))  # composes a coma separated string with the contents of a.list

result:

a,"1,2,3"

(quotes protecting the commas so it is seen as a single cell)

Comments