W. Zhu
W. Zhu

Reputation: 825

Return value of CSV writer's writerow method inconsistent with the length of the text written

I am using python 3.5.2 on Windows. I tested a sample data 'a, b, c' with csv writer's writerow method, which returned 7. However, when I read that file, the length of the text was only 6. Why did this happen?

>>> import csv
>>> fp = open("C:\\Users\\neem\\Desktop\\CSV.csv", "w", newline="")
>>> writer = csv.writer(fp)
>>> writer.writerow(['a', 'b', 'c'])
7
>>> fp.close()
>>> fp = open("C:\\Users\\neem\\Desktop\\CSV.csv")
>>> text = fp.read()
>>> text
'a,b,c\n'
>>> len(text)
6

Upvotes: 0

Views: 594

Answers (2)

BrendanSimon
BrendanSimon

Reputation: 711

If you hexdump the file, or read it in binary mode, then you should see the "\r\n" at the end of the text (on Windows platform).

Upvotes: 0

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18467

I can't find anywhere in versions 2.6 - 3.5 where

  • the return value of writerow is documented
  • much less guaranteed to return the number of characters written as interpreted by Python
  • use of the return value of writerow is documented

That all tells me that it's not meant for public consumption, so I'm a little confused as to why you've built up any expectations around its behavior.

That said, in your particular case, this "discrepancy" is almost certainly due to line endings. Since you're on Windows, Python is helpfully ending your lines with \r\n, where as you're measuring the length of the line with only \n, hence the missing character.

Upvotes: 1

Related Questions