Python 2 CSV writer produces wrong line terminator on Windows

In Python 2.x, always open your file in binary mode, as documented. csv writes \r\n as you expected, but then the underlying Windows text file mechanism cuts in and changes that \n to \r\n … total effect: \r\r\n

From the csv.writer documentation:

If csvfile is a file object, it must be opened with the 'b' flag on platforms where that makes a difference.

There seems to be some reticence about actually uttering the name of the main culprit 🙂

Edit: As mentioned by @jebob in the comments to this answer and based on @Dave Burton’s answer, to handle this case in both Python 2 and 3, you should do the following:

if sys.version_info >= (3,0,0):
    f = open(filename, 'w', newline="")
else:
    f = open(filename, 'wb')

Leave a Comment