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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Akshay
  • 833
  • 2
  • 16
  • 34
  • 1
    Have you tried anything yourself yet? What problems did you encounter? – Martijn Pieters Oct 24 '13 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 – Akshay Oct 24 '13 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. – Martijn Pieters Oct 24 '13 at 20:30

2 Answers2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • As seedubbs in their answer mentions, "TypeError: 'newline' is an invalid keyword argument for this function". – samkhan13 Mar 11 '17 at 22:34
  • 1
    @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). – Martijn Pieters Mar 11 '17 at 23:18
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)
seedubbs
  • 31
  • 1