3

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.

5
  • 7
    Show us your code. Commented May 9, 2014 at 20:57
  • If I understand your last part right, do you want a b c, d e f,? Commented May 9, 2014 at 20:58
  • could you write for lst in wholeList: csv.writerow(lst)? This yould write every row in another line of the file (or at least i think so). Commented May 9, 2014 at 20:58
  • Why are you using writerow and not writerows? Commented May 9, 2014 at 20:58
  • 1
    That is a list of tuples not a list of lists Commented May 9, 2014 at 21:07

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

3

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"

1 Comment

Perfect! Thank you and everyone very much for responding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.