Search code examples
pythoncsvstringio

python convert list of strings to CSV


I have a list of strings like so:

ls = [
'Header1,Header2,Header3',
'Value1,Value2,Value3',
'Value4,Value5,Value6'
]

And I want to convert it to a CSV or CSV Object with the format:

+-------+-------+-------+
|Header1|Header2|Header3|
-------------------------
|Value1 |Value2 |Value3 |
|Value4 |Value5 |Value6 |

Currently, I have tried:

import csv
import io

f = io.StringIO()
writer = csv.writer(f)
for i in range(len(ls)):
    writer.writerow(ls[i])

reader = csv.DictReader(f)
f.getvalue()

But it returns something like this:

'H,E,A,D,E,R,1,",",H,E,A,D,E,R,2,",",H,E,A,D,E,R,3,",",V,A,L,U,E,1,","

etc

What am I doing wrong?


Solution

  • Split your strings into iterable arrays before adding them to a row:

    for i in range(len(ls)):
      ls[i] = ls[i].split(',')
      writer.writerow(ls[i])
    

    Repl.it

    As you found out, not doing so will iterate over the string character by character. This way, each element of the array will be iterated as a whole.