Andrew Lauer Barinov Andrew Lauer Barinov - 1 year ago 100
Python Question

Writing List of Strings to Excel CSV File in Python

I am 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 the CSV.writer to delimit every individual string within the list rather than every character? In this case, I am using Python 2.6 on Snow Leopard.

I checked the Python guide and couldn't find anything specific:

import csv

# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File
resultFyle = open("output.csv",'wb')

# Create Writer Object
wr = csv.writer(resultFyle, dialect='excel')

# Write Data to File
for item in RESULTS:

Answer Source

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


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

Do either:

import csv
resultFile = open("output.csv",'wb')
wr = csv.writer(resultFile, dialect='excel')


import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
resultFile = open("output.csv",'wb')
wr = csv.writer(resultFile, dialect='excel')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download