Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write List of lists in csv file in python

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.

like image 672
Akshay Avatar asked Oct 24 '13 19:10

Akshay


2 Answers

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.

like image 177
Martijn Pieters Avatar answered Oct 26 '22 23:10

Martijn Pieters


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)
like image 33
seedubbs Avatar answered Oct 27 '22 00:10

seedubbs