Home > Software design >  List of lists to csv with commas to separate fields and newlines to separate rows
List of lists to csv with commas to separate fields and newlines to separate rows

Time:02-16

I tried doing what was suggested in this question but this does not seem to give me the right output. Instead the csv file seems to interpret each sublist as a field. Instead each value in a sublist should be a field for one row.

An example

Dummy data:

test=[['a','1','!'],['b','2','?']]

My current code:

with open('./csv_files/CtMLI.csv', 'w', newline="\n") as myfile:
    wr = csv.writer(myfile)
    wr.writerow(test)

Output of code (CtMLI.csv):

"['a', '1', '!']","['b', '2', '?']"

Desired output (of CtMLI.csv):

'a', '1', '!'
'b', '2', '?'

What am I doing wrong?

CodePudding user response:

You should use writerows instead of writerow.

import csv

test=[['a','1','!'],['b','2','?']]

with open('./csv_files/CtMLI.csv', 'w', newline="\n") as myfile:
    wr = csv.writer(myfile)
    wr.writerows(test)
  • Related