Wednesday, February 9, 2011

Converting Tabs to Spaces

Mixing tabs and spaces in Python is a bad thing. In recent Python, Python will complain if there are such occurrences. Here I'm gonna show you a small tool to convert tabs to spaces.
import os, sys

def _error(msg):
    print "Error:", msg
    sys.exit(1)
    
def tab2space(path, numspace):
    """ Convert tabs to spaces """
    if not os.path.exists(path): _error(path + "does not exist")
    print "Converting tabs to spaces..."
    origfile = open(path, "r")
    origfilename = origfile.name
    tmpfile = open(path + ".tmp", "w")
    tmpfilename = tmpfile.name
    try:
        for l in origfile.readlines():
            newline = l.replace("\t", " " * numspace)
            tmpfile.write(newline)
    finally:
        # It is important to close the open files; otherwise the
        # remove statement below may not work, especially on Windows.
        tmpfile.close()
        origfile.close()
    os.remove(origfilename)
    os.rename(tmpfilename, origfilename)
    print "*** Done ***"

def _usage(progname):
    print "Usage:", progname, "<path> <number of spaces>"
    sys.exit(1)
    
if __name__ == "__main__":
    if len(sys.argv) != 3: _usage(sys.argv[0])
    tab2space(sys.argv[1], int(sys.argv[2]))

Enjoy!

No comments:

Post a Comment