How to write list of lists in csv file in python

I have a list of lists and I want to write it to a csv file List of examples:

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

data [0] should be column names; everything else is data in a row.

Please suggest me a way to do this.

+7
source share
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 a header in data as the first line; you can write all the lines in one writer.writerows() using the writer.writerows() method. That’s all there really is.

+12
source

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 great for me.

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

Source: https://habr.com/ru/post/956674/


All Articles