python – Deleting carriage returns caused by line reading

python – Deleting carriage returns caused by line reading

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 + ,)


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))


or Just using List COmprehension

>>> with open(test.txt) as fin:
    print ,.join(e.strip(n) for e in  fin)


You can use .rstrip() to remove newlines from the right-hand side of a string:


or you can tell it to remove all whitespace (including spaces, tabs and carriage returns):


It is a more specific version of the .strip() method which removes whitespace or specific characters from both sides of the string.

For your specific case, you could stick with a simple .strip() but for the general case where you want to remove only the newline, Id stick with `.rstrip(n).

Id use a different method to write your strings though:

with open(list.txt) as input_file:
    print ,.join([{}.format(line.rstrip(n)) for line in input_file])

By using ,.join() you avoid the last comma, and using the str.format() method is easier on the eyes than a lot of string concatenation (not to mention faster).

python – Deleting carriage returns caused by line reading

First of all, in order to make it all appear on one line you should get rind of the n. I find line.rstrip(n) to work nicely.

In order to get rid of the , at the end I would put all of the words in a list adding the quotation marks. Then using join(), join all of the words in the list with ,

temp = []
for line in file:
    i = line.rstrip(n)
    word = +i+
print ,.join(temp)

That should get the desired output

Leave a Reply

Your email address will not be published. Required fields are marked *