Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace \r\n for \n in CSV Writer

I am currently opening and writing a CSV file like this in python:

with open('Data.csv', 'wb') as redata_csv:
    csv_writer = csv.writer(redata_csv, delimiter=',')

however, each new line ends with \r\n, and I would like it to end with just \n instead. I can't find how...

like image 859
abisson Avatar asked Dec 08 '22 16:12

abisson


2 Answers

Use the lineterminator keyword argument.

Both the reader and writer classes support the creation of a custom anonymous dialect via keyword arguments. You are already doing that in part by setting delimiter - adding lineterminator gets you an anonymous dialect that is delimited by commas and is terminated by line feeds.

like image 86
Sean Vieira Avatar answered Dec 11 '22 11:12

Sean Vieira


csv.writer(reindentified_csv, delimiter=',', lineterminator='\n')

csv.writer Documentation:

csv.writer(csvfile, dialect='excel', **fmtparams)

...

The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.

Dialects and Formatting Parameters:

lineterminator

The string used to terminate lines produced by the writer. It defaults to '\r\n'.

like image 32
Pavel Anossov Avatar answered Dec 11 '22 11:12

Pavel Anossov