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

我们两清 提交于 2019-12-04 22:14:06

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!