Home > Software engineering >  write multiple lists to csv (one is a nested list)
write multiple lists to csv (one is a nested list)

Time:10-20

I have say three lists, and one of them is nested like so:

a = [1, 2, 3, 4]
b = ["abc", "def", "dec", "erf"]
c = [[5, 6, 7], [8, 9, 10], [11, 12, 13.3], [14, 15, 16]]

I would like a CSV file output of it which looks like this:

1,abc,5,6,7
2,def,8,9,10
3,erf,11,12,13.3
...

I tried zipping them and writing to a CSV file like so:

with open('filer.csv', "w") as f:
    writer = csv.writer(f)
    for row in zip(a, b, c):
        writer.writerow(row)

but the output has these stupid brackets like so:

1,abc,"[5,6,7]"
2,def,"[8,9,10]"
3,erf,"[11,12,13.3]"
...

but I want them without brackets and without the quotes like so:

1,abc,5,6,7
2,def,8,9,10
3,erf,11,12,13.3
...

:(

CodePudding user response:

Use:

with open('filer.csv', "w") as f:
    writer = csv.writer(f)
    for ai, bi, ci in zip(a, b, c):
        writer.writerow([ai, bi, *ci])

Output

1,abc,5,6,7
2,def,8,9,10
3,dec,11,12,13.3
4,erf,14,15,16

As you said you have nested list, so you need to flatten the list, the expression [ai, bi, *ci] flattens it.

The reason that you get the brackets is that writerow is (probably) applying the function str for each element of the iterable passed to it. And the string representation of a list includes the brackets, for example:

In[3]: str([1, 2, 3])
Out[3]: '[1, 2, 3]'
  • Related