Luca Guarro
Luca Guarro

Reputation: 1168

List of lists to csv with commas to separate fields and newlines to separate rows

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?

Upvotes: 0

Views: 805

Answers (1)

Zack
Zack

Reputation: 104

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)

Upvotes: 1

Related Questions