How to convert python3 csv representation as list to valid csv data using the `csv` module

Question:

I have such list:

[["1", "2"], ["3", "4"], ["bacon", "eggs"]]

And I want to convert it to csv using
the csv module safely, so it’d look
something like this:

1,2
3,3
bacon,eggs

But I cannot find a way to do it, is there even
a way to do it? What should I use to do such thing,
I don’t want to write it to a temporary file, I want
it to be all in-memory, for example how I parsed
it into a list in the first place:

list(csv.reader(StringIO(data.decode())))

StringIO is from the io module

If it matters this application is for UNIX-like only

Thanks for the answers in advance 🙂

Asked By: Ari157

||

Answers:

If you want to use StringIO with csv module you can use next example:

import csv
from io import StringIO

data = [["1", "2"], ["3", "4"], ["bacon", "eggs"]]

with StringIO() as f_out:
    w = csv.writer(f_out)
    w.writerows(data)

    # print the contents of f_out:
    f_out.seek(0)
    print(f_out.read())

Prints:

1,2
3,4
bacon,eggs
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.