Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - csv: writer.writerows() splitting my string inputs

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...