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?
You can give your
writer
instance a customlineterminator
argument in the constructor: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 specifynewline=''
for Python 3 (see this comment).Old solution (Python 2 only)
In Python 2, use
'wb'
mode (see the docs).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'
andos.linesep
, your line endings should be correct on all platforms.