12

I have a list of lists and I want to write it in csv file Example list:

data=[['serial', 'name', 'subject'],['1', 'atul','tpa'],['2', 'carl','CN'].......]

data[0] should be column names everything else is row wise data

Please suggest me a way to do this.

3
  • 1
    Have you tried anything yourself yet? What problems did you encounter? Commented Oct 24, 2013 at 20:00
  • actully I have multiple sheets in excel file and I parsed all the sheets and created a list of lists. So when I am writing it into csv file with your solution it's pasting column names for each and every sheet Commented Oct 24, 2013 at 20:29
  • csv is just writing out what you give it. Skip the first entry of every sheet but the first if you see duplicate column names. Commented Oct 24, 2013 at 20:30

2 Answers 2

20

This is trivial with the csv module:

with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(data)

You already have the header in data as the first row; you can write all rows in one go with the writer.writerows() method. That's all there is to it, really.

Sign up to request clarification or add additional context in comments.

2 Comments

As seedubbs in their answer mentions, "TypeError: 'newline' is an invalid keyword argument for this function".
@samkhan13: you and they are using Python 2, not Python 3 (note the question tags). Use open('output.csv', 'wb') instead (so use binary mode so the CSV module can control what newlines are written).
2

I get the following error when I include newline='': TypeError: 'newline' is an invalid keyword argument for this function.

This is what I used and worked fine for me.

csv_file = open("your_csv_file.csv", "wb")
writer = csv.writer(csv_file)
writer.writerows(clean_list)

1 Comment

That's because you are using Python 2, not Python 3, as tagged on the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.