kamal kamal - 1 year ago 88
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.lstrip() # to remove leading white space
foo.rstrip() # to remove trailing whitespace
foo.strip() # to remove both lead and trailing whitespace

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download