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:
http://www.python.org/dev/peps/pep-0305/#managing-different-dialects
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:
wr.writerow(item)
解决方案
The csv.writer writerow method takes an iterable as 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",'wb') as resultFile:
wr = csv.writer(resultFile, dialect='excel')
wr.writerows(RESULTS)
or:
import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open("output.csv",'wb') as resultFile:
wr = csv.writer(resultFile, dialect='excel')
wr.writerow(RESULT)