Does Python csv writer always use DOS end-of-line characters?
PythonCsvLine EndingsWriterPython Problem Overview
I realize that the csv library in Python always generates DOS end-of-line characters. Even if I use the 'wb'
mode, even if I use Linux.
import csv
f = open('output.txt', 'wb');
writer = csv.writer(f)
writer.writerow([2,3,4]);
f.close()
The above code always uses '\r\n'
as the end of line separator. How can I make it use use '\n'
only?
Python Solutions
Solution 1 - Python
You can give your writer
instance a custom lineterminator
argument in the constructor:
writer = csv.writer(f, lineterminator="\n")
Solution 2 - Python
As Niklas answered, the lineterminator argument lets you choose your line endings. Rather than hard coding it to '\n'
, make it platform independent by using your platform's line separator: os.linesep
. Also, make sure to specify newline=''
for Python 3 (see this comment).
import csv
import os
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f, lineterminator=os.linesep)
writer.writerow([2, 3, 4])
Old solution (Python 2 only)
In Python 2, use 'wb'
mode (see the docs).
import csv
import os
with open('output.csv', 'wb') as f:
writer = csv.writer(f, lineterminator=os.linesep)
writer.writerow([2, 3, 4])
For others who find this post, don't miss the 'wb'
if you're still using Python 2. (In Python 3, this problem is handled by Python). You won't notice a problem if you're missing it on some platforms like GNU/Linux, but it is important to open the file in binary mode on platforms where that matters, like Windows. Otherwise, the csv file can end up with line endings like \r\r\n
. If you use the 'wb'
and os.linesep
, your line endings should be correct on all platforms.