Skip to content Skip to sidebar Skip to footer

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.wr

Solution 1:

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

Solution 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"

Post a Comment for "How To Write List Of Lists To Csv File Python?"