Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python csv writer remove carriage returns

Tags:

python-3.x

csv

Can somebody helps how to remove ^M end of line ? I am using Unix system. This is default sample script from csv python docu, I use similar scenario in my script with same results :(

import csv

with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

like image 547
andrew Avatar asked Sep 10 '26 15:09

andrew


1 Answers

The ^M is the carriage-return character (\r - 0x0d).

So you probably have \r or \r\n (0x0d 0x0a) at the end of each line.

Maybe you could try with:

with open('names.csv', 'w', newline='\n') as csvfile:

or:

with open('names.csv', 'w', newline='\x0a') as csvfile:
like image 71
Danny_ds Avatar answered Sep 13 '26 09:09

Danny_ds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!