csv: writer.writerows() splitting my string inputs

后端 未结 4 876
予麋鹿
予麋鹿 2020-12-09 19:37

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, \']
<         


        
4条回答
  •  醉话见心
    2020-12-09 20:33

    Most likely your list_results contains something like:

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

    writerows() takes a list of lists, you supply a list of strings, a string is iterable and is thus converted into list of chars, what you want is:

    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.split(',')] for r in list_results)
    

提交回复
热议问题