Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

csv: writer.writerows() splitting my string inputs

Tags:

python

csv

I have a list of strings which I would like to write to a csv file. The list list_results looks like

['False, 60, 40 ', 'True, 70, 30, ']

So, I would try something like this:

with open('example1.csv', 'w') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow( ('Correct?', 'Successes', 'Failures') )
    writer.writerows(list_results)

Unfortunately, the data doesn't write into three columns. I find:

['Correct?', 'Successes', 'Failures']  
['F', 'a', 'l', 's', 'e', ',', ' ', '6', '0', ',', ' ', '4', '0', ' ']  
['T', 'r', 'u', 'e', ',', ' ', '7', '0', ',', ' ', '3', '0', ',', ' ']

How do I format this behavior appropriately to get

['Correct?', 'Successes', 'Failures']  
['False', 60, 40]  
['True', 70, 30]

Preferably in format %s %d %d ?

like image 265
ShanZhengYang Avatar asked Dec 15 '15 09:12

ShanZhengYang


People also ask

Why does Csvwriter Writerow () put a comma after each character?

This happens, because when group() method of a MatchObject instance returns only a single value, it returns it as a string. When there are multiple values, they are returned as a tuple of strings.

What is the default delimiter for CSV writer?

By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma.

How do I write a string in a CSV file?

Steps for writing a CSV file First, open the CSV file for writing ( w mode) by using the open() function. Second, create a CSV writer object by calling the writer() function of the csv module. Third, write data to CSV file by calling the writerow() or writerows() method of the CSV writer object.

What is writer Writerow?

writerow(): This method writes a single row at a time. Field row can be written using this method. Syntax: writerow(fields) writerows(): This method is used to write multiple rows at a time. This can be used to write rows list.


1 Answers

You are using writer.writerows() with an s at the end. That method expects a list of lists, but you passed in a list of strings. The writerows() method essentially does this:

def writerows(self, rows):
    for row in rows:
        self.writerow(row)

where each row must be a sequence of columns. A string is a sequence of individual characters, so that's what you get written: individual characters separated by your chosen delimiter.

You'll need to split out your string into columns, don't include the commas yourself, it's the job of the writer object to include those:

with open('example1.csv', 'w') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow(('Correct?', 'Successes', 'Failures'))
    for row in list_results:
        columns = [c.strip() for c in row.strip(', ').split(',')]
        writer.writerow(columns)

or using a generator expression so you can keep using writerows():

with open('example1.csv', 'w') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow(('Correct?', 'Successes', 'Failures'))
    writer.writerows([c.strip() for c in r.strip(', ').split(',')]
                     for r in list_results)

Demo:

>>> import csv
>>> list_results = ['False, 60, 40 ', 'True, 70, 30, ']
>>> import csv
>>> import sys
>>> list_results = ['False, 60, 40 ', 'True, 70, 30, ']
>>> writer = csv.writer(sys.stdout)
>>> writer.writerow(('Correct?', 'Successes', 'Failures'))
Correct?,Successes,Failures
>>> for row in list_results:
...     columns = [c.strip() for c in row.strip(', ').split(',')]
...     writer.writerow(columns)
...
False,60,40
True,70,30
>>> writer.writerows([c.strip() for c in r.strip(', ').split(',')]
...                  for r in list_results)
False,60,40
True,70,30
like image 195
Martijn Pieters Avatar answered Oct 22 '22 05:10

Martijn Pieters