简体   繁体   中英

How to write list of lists to CSV file Python?

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.

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM