Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 944
CuriousMind Avatar asked Mar 23 '12 19:03

CuriousMind


People also ask

Why is csv Writer adding newline?

This function in csv module returns a writer object that converts data into a delimited string and stores in a file object. The function needs a file object created with open() function and with write permission as a parameter. Every row written in the file issues a newline character by default.

What is newline in Python csv?

Python's file objects, by default, use universal newlines when reading files. That means that any of '\n' , '\r' and '\r\n' strings are translated into '\n' when you read a file.

Do you need to close a CSV file in Python?

Close a CSV FileIt's a good practice to close the file once you are finished with it. You don't want an open file running around taking up resources! Use the close() function to close an open file.


1 Answers

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

writer = csv.writer(f, lineterminator="\n") 
like image 96
Niklas B. Avatar answered Sep 25 '22 01:09

Niklas B.