Chipmunkafy
Chipmunkafy

Reputation: 586

List array as one cell when using .writerow()

Write to CSV:

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam', 'WOW', '['HMM', 'WOW']', 'BYE'])
    spamwriter.writerow(['Cool', 'Nice'])

Excel Output Unexpected:

Expected Excel Output: enter image description here

How would I keep ['HMM', 'WOW'] all in cell C?

Upvotes: 0

Views: 150

Answers (1)

dabljues
dabljues

Reputation: 1937

The problem is, that you are using a delimiter , but also trying to put that , into a cell. That's not gonna work. You can try using:

with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=';',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)

And then change your OS regional settings, so your Office app would recognize ; as a delimiter in spreadsheets. Otherwise, you have to get rid of , in a cell

Also, at least for me, it throws an error, cuz you didn't escape ' symbol properly when defining your list. I had to change it to:

spamwriter.writerow(['Spam', 'WOW', "['HMM', 'WOW']", 'BYE'])

The result of using ; as a delimiter:

enter image description here

Upvotes: 2

Related Questions