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.
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.
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.
writerows() This function takes a list of iterables as parameter and writes each item as a comma separated line of items in the 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.
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)
Very simple to fix, you just need to turn the parameter to writerow
into a list.
for item in RESULTS: wr.writerow([item])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With