Tuesday, March 1, 2011

How to Remove Trailing Spaces in Python

Although most text editors provide this feature, just for fun, below is a Python script to do that :) This script preserves the newlines.

#!/usr/bin/env python

import sys, os

def del_trailing_spaces(path):
    if not os.path.exists(path): _error(path + "doesn't exist")
    f = open(path, "rb")
    lines = f.readlines()
    f.close()

    f = open(path, "wb")
    for line in lines:
        if line[len(line)-2] == '\r' and line[len(line)-1] == '\n':
            f.write(line[:len(line)-2].rstrip() + line[len(line)-2] +
                    line[len(line)-1]) 
        elif line[len(line)-1] == '\n' or line[len(line)-1] == '\r':
            f.write(line[:len(line)-1].rstrip() + line[len(line)-1])
        else:
            f.write(line.rstrip())
    f.close()                                    

def _error(msg):
    print "Error:", msg
    sys.exit(1)
    
if __name__ == "__main__":
    if len(sys.argv) != 2: _error("invalid argument")
    del_trailing_spaces(sys.argv[1])

No comments:

Post a Comment