pythoncsv

Writing List of Strings to Excel CSV File in Python


I'm trying to create a csv file that contains the contents of a list of strings in Python, using the script below. However when I check my output file, it turns out that every character is delimited by a comma. How can I instruct csv.writer to delimit every individual string within the list rather than every character?

import csv

RESULTS = ['apple','cherry','orange','pineapple','strawberry']

result_file = open("output.csv",'wb')
wr = csv.writer(result_file, dialect='excel')
for item in RESULTS:
    wr.writerow(item)

I checked PEP 305 and couldn't find anything specific.


Solution

  • The csv.writer writerow method takes an iterable as an argument. Your result set has to be a list (rows) of lists (columns).

    csvwriter.writerow(row)
    

    Write the row parameter to the writer’s file object, formatted according to the current dialect.

    Do either:

    import csv
    RESULTS = [
        ['apple','cherry','orange','pineapple','strawberry']
    ]
    with open('output.csv','w') as result_file:
        wr = csv.writer(result_file, dialect='excel')
        wr.writerows(RESULTS)
    

    or:

    import csv
    RESULT = ['apple','cherry','orange','pineapple','strawberry']
    with open('output.csv','w') as result_file:
        wr = csv.writer(result_file, dialect='excel')
        wr.writerow(RESULT)