Domanda

I have a list of lists like [('a', 'b', 'c'), ('d', 'e', 'f'),....]. I want to write it to a CSV file like this-

a,   b,   c
d,   e,   f

How do I do that?

I've tried using csv.writerows but the output file had each character in different cells and all together in same row. In the sense, the cells in row one had ' a ' ' b ' etc.

Thanks.

È stato utile?

Soluzione 2

If you have Pandas, it's pretty easy and fast. I assume you have a list of tuples called "data".

import pandas as pd
data = [('a', 'b', 'c'), ('d', 'e', 'f')]
df = pd.DataFrame(data)
df.to_csv('test.csv', index=False, header=False)

done!

EDIT: "list of lists" -> "list of tuples"

Altri suggerimenti

Use writer.writerows() (plural, with s) to write a list of rows in one go:

>>> import csv
>>> import sys
>>> data = [('a', 'b', 'c'), ('d', 'e', 'f')]
>>> writer = csv.writer(sys.stdout)
>>> writer.writerows(data)
a,b,c
d,e,f
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top