'What does the csv.writerow() method return?

I am learning how to write to a CSV file using the built-in csv module.

I open the file using the below code:

file_to_output=open('to_save_file.csv', mode='w', newline='')

Then I create a csv writer object:

csv_writer = csv.writer(file_to_output, delimiter=',')

Then I write a row using writerow:

csv_writer.writerow(['a', 'b', 'c'])

Now, this function returns 7.

Many posts say that this number is the number of characters written, but when I close and check the file, only 5 characters are written to the file, i.e., a,b,c.

What does this number signify?



Solution 1:[1]

Just going off the docs:

csvwriter.writerow(row):

... Return the return value of the call to the write method of the underlying file object.

TextIOBase.write(s):

... return the number of characters written.

So the answer to the question is technically whatever the underlying write method returns, which in your example (a TextIOBase file) is the number of characters written.

But, pragmatically, @accdias is right, you're seeing the effect of the default dialect using CRLF. I'm using a Mac, too, 12.1:

import csv

writer = csv.writer(open('output.csv', 'w', newline=''))
writer.writerow(['a','b','c'])
% hexdump -C output.csv
00000000  61 2c 62 2c 63 0d 0a                              |a,b,c..|
00000007

From the csv module source:

class excel(Dialect):
    """Describe the usual properties of Excel-generated CSV files."""
    delimiter = ','
    quotechar = '"'
    doublequote = True
    skipinitialspace = False
    lineterminator = '\r\n'
    quoting = QUOTE_MINIMAL

You can change dialect= or lineterminator= when you instantiate writer():

writer = csv.writer(open('output.csv', 'w', newline=''), lineterminator='\n')

and now I get:

00000000  61 2c 62 2c 63 0a                                 |a,b,c.|
00000006

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1