kamal kamal - 4 months ago 8
Python Question

How to remove trailing whitespace in code, using another script?

Something like:

import fileinput

for lines in fileinput.FileInput("test.txt", inplace=1):
lines = lines.strip()
if lines == '': continue
print lines


But nothing is being printed on stdout.

Assuming some string named
foo
:

foo.lstrip() # to remove leading white space
foo.rstrip() # to remove trailing whitespace
foo.strip() # to remove both lead and trailing whitespace

Answer

fileinput seems to be for multiple input streams. This is what I would do:

with open("test.txt") as file:
    for line in file:
        line = line.rstrip()
        if line:
            print line