Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading