[python] 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.

This question is related to python csv

The answer is


A sample - write multiple rows with boolean column (using example above by GaretJax and Eran?).

import csv
RESULT = [['IsBerry','FruitName'],
          [False,'apple'],
          [True, 'cherry'],
          [False,'orange'],
          [False,'pineapple'],
          [True, 'strawberry']]
with open("../datasets/dashdb.csv", 'wb') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    wr.writerows(RESULT)

Result:

df_data_4 = pd.read_csv('../datasets/dashdb.csv')
df_data_4.head()

Output:

   IsBerry  FruitName
   0    False   apple
   1    True    cherry
   2    False   orange
   3    False   pineapple
   4    True    strawberry

I know I'm a little late, but something I found that works (and doesn't require using csv) is to write a for loop that writes to your file for every element in your list.

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

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

# Write data to file
for r in RESULTS:
    resultFyle.write(r + "\n")
resultFyle.close()

I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.


Very simple to fix, you just need to turn the parameter to writerow into a list.

for item in RESULTS:
     wr.writerow([item,])