How do I remove whitespace at the end of all lines in a file in Python?

105 views Asked by At

I'm a bit new and can't configure the rstrip command to do what I want.

I did some string manipulation on a file which worked great, and I've written the results to a new file. That new file now just needs the trailing whitespace removed from the end of all the lines.

My code that doesn't work goes like this:

fo = open( FILENAME, 'r+' )
data_l = fo.read()
data = data_l.rstrip
fo.write(data)

This gives me an error:

    fo.write(data)
TypeError: expected a character buffer object

I'm guessing this is to do with me reading and writing to the same file? I tried looking into this but all the solutions looked verbose and complex and I feel this is probably quite a simple, common task.

So my question is, what's a good way of doing this?

2

There are 2 answers

0
Mike Müller On BEST ANSWER

This is one way of doing it, sing a temporary file:

import shutil
import tempfile


tmp = tempfile.mktemp()
with open(FILENAME) as fobj_in, open(tmp, 'w') as fobj_out:
    for line in fobj_in:
        fobj_out.write(line.rstrip() + '\n')
shutil.move(tmp, FILENAME)

Reading and writing to the same file will be more complicated. You won't gain much (any?) performance because you need to write the data anyway. Just deleting something in the middle of a file means re-writing all the rest of the file content.

2
doctorlove On

If you call data = data.rstrip you have squirrelled away the function, rather than called it:

Given

>>> data_l = 'hello           '

notice

>>> data_wrong = data_l.rstrip
>>> type(data_wrong)
<type 'builtin_function_or_method'>

whereas

>>> data_right = data_l.rstrip()
>>> data_right
'hello'

so you probably want

fo = open ( FILENAME, 'r+' )
data_l = fo.read()
data = data.rstrip()  #call the function
fo.write(data)        #I assume you meant this instead of data_l