Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.writerow() csv returns a number instead of writing rows

I am testing some really simple code with Python 3. For some reason, the following code generates an empty output, instead of writing a line

import csv

output = open('hello world.csv', 'w',newline='')
wr = csv.writer(output, quoting=csv.QUOTE_ALL)

wr.writerow('hello world')

If I try the commands in the interpreter, .writerow() returns a number. The following example is the one used in the documentation page:

>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w', newline=''), delimiter=' ',
... quotechar='|', quoting=csv.QUOTE_MINIMAL)
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
40
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
37
like image 340
Francesco Della Vedova Avatar asked Feb 19 '23 22:02

Francesco Della Vedova


1 Answers

writerow actually writes rows but you don't see them in eggs.csv because of file buffering. To see something in the file close it or call .flush() method. If you use with-statement then the file is closed automatically even if there is an error.

It is not documented (report a bug?) but writerow returns the result of fileobj.write() method i.e. number of characters written to a file in this case.

You should pass a sequence of fields that form a row to writerow method:

writer.writerow(['field 1', 'field 2', 'etc'])

If you pass a string instead of a list then the string is interpreted as a sequence of fields where each field is an individual character:

#XXX this is probably not what you want, don't do it
writer.writerow('abc')
# -> a,b,c
like image 184
jfs Avatar answered Feb 27 '23 14:02

jfs