Does Python csv writer always use DOS end-of-line characters? Does Python csv writer always use DOS end-of-line characters? python python

Does Python csv writer always use DOS end-of-line characters?


You can give your writer instance a custom lineterminator argument in the constructor:

writer = csv.writer(f, lineterminator="\n")


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 csvimport oswith 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 csvimport oswith 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.