54

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.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Andrew Lauer Barinov
  • 5,694
  • 10
  • 59
  • 83
  • 3
    I excel is the default dialect, you don't need to specify it. – agf Aug 02 '11 at 18:13
  • I know you asked this question a long time ago, but I've got to know - if you're only putting a single item in each row, why do you need to use `csv`? – Mark Ransom Apr 26 '21 at 16:05

4 Answers4

96

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)
GaretJax
  • 7,462
  • 1
  • 38
  • 47
  • 1
    Link to documentation: [csv module, Writer Objects](http://docs.python.org/library/csv.html?highlight=csv#writer-objects) – crashmstr Aug 02 '11 at 18:14
  • @Andrew: The second one works too, an if you need to write a single row, it is probably more appropriate (you may want to mark the answer as accepted if it solved your issue). – GaretJax Aug 02 '11 at 18:18
  • @crashmstr: Thanks, added the link inline too. – GaretJax Aug 02 '11 at 18:19
  • how can we manage the formats(date,string,number ...) when inserting into the excel file ? – user1863359 Aug 29 '14 at 10:40
  • @user1863359 unfortunately CSV files don't contain any formatting information. Excel itself will make a guess on the appropriate format for each column. Sometimes it guesses wrong: [Scientists rename human genes to stop Microsoft Excel from misreading them as dates](https://www.theverge.com/2020/8/6/21355674/human-genes-rename-microsoft-excel-misreading-dates). – Mark Ransom Sep 10 '21 at 21:17
36

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

for item in RESULTS:
    wr.writerow([item])
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
9

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.

cass
  • 858
  • 1
  • 10
  • 17
  • 2
    The main problem with writing csv files without using the `csv` module is that if your values contain quotes or commas, your file will be broken. – Boris Verkhovskiy Oct 04 '19 at 00:05
3

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
Ragu
  • 31
  • 3