Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing List of Strings to Excel CSV File in Python

Tags:

python

csv

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.

like image 631
Andrew Lauer Barinov Avatar asked Aug 02 '11 18:08

Andrew Lauer Barinov


People also ask

How do I write a list of elements in a CSV file in Python?

csv is the name of the file, the “w” mode is used to write the file, to write the list to the CSV file write = csv. writer(f), to write each row of the list to csv file writer. writerow() is used.

How do I make a list into a CSV file?

The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating a CSV file and writing data row-wise into it using writer class.

What method takes a list argument and write it to a CSV file?

writerows() This function takes a list of iterables as parameter and writes each item as a comma separated line of items in the file.

How do I write a string in a CSV file?

writer () is used to insert data into CSV file as we require to write a string to CSV file without quotes so I used QUOTE_NONE to get a file without quotes. To write all the elements in rows writer. writerow() is used.


2 Answers

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) 
like image 87
GaretJax Avatar answered Oct 21 '22 01:10

GaretJax


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

for item in RESULTS:     wr.writerow([item]) 
like image 28
Mark Ransom Avatar answered Oct 21 '22 02:10

Mark Ransom