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 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
.
import csv
import os
f = open('output.csv', 'wb')
writer = csv.writer(f, lineterminator=os.linesep)
writer.writerow([2,3,4])
f.close()
For others who find this post, don't miss the 'wb'
. 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.
来源:https://stackoverflow.com/questions/9845681/does-python-csv-writer-always-use-dos-end-of-line-characters