Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting carriage returns caused by line reading

Tags:

I have a list:

Cat Dog Monkey Pig 

I have a script:

import sys input_file = open('list.txt', 'r') for line in input_file:     sys.stdout.write('"' + line + '",') 

The output is:

"Cat ","Dog ","Monkey ","Pig", 

I'd like:

"Cat","Dog","Monkey","Pig", 

I can't get rid of the carriage return that occurs from processing the lines in the list. Bonus point for getting rid of the , at the end. Not sure how to just find and delete the last instance.

like image 437
Chris J. Vargo Avatar asked Feb 21 '13 16:02

Chris J. Vargo


People also ask

How do I disable a carriage return line feed?

In the Find box hold down the Alt key and type 0 1 0 for the line feed and Alt 0 1 3 for the carriage return. They can now be replaced with whatever you want.


1 Answers

str.rstrip or simply str.strip is the right tool to split carriage return (newline) from the data read from the file. Note str.strip will strip of whitespaces from either end. If you are only interested in stripping of newline, just use strip('\n')

Change the line

 sys.stdout.write('"' + line + '",') 

to

sys.stdout.write('"' + line.strip() + '",') 

Note in your case, a more simplistic solution would had been

>>> from itertools import imap >>> with open("list.txt") as fin:     print ','.join(imap(str.strip, fin))   Cat,Dog,Monkey,Pig 

or Just using List COmprehension

>>> with open("test.txt") as fin:     print ','.join(e.strip('\n') for e in  fin)   Cat,Dog,Monkey,Pig 
like image 190
Abhijit Avatar answered Oct 09 '22 22:10

Abhijit