faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

Converting file names with "%xx" in them

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 227, Python Snippet Support Team


"""
Packages: tools
"""
# convperc.py
# Convert file names with "%" in them, e.g.
# "My%20name.txt" -> "My name.txt"
# Useful for renaming files which were saved by a webcrawler or browser.
# Often files get stored as "My%20file.html" rather than "My file.html".
# This script renames such files.
#
# 25 Oct 1999: Works recursively now if you specify the -s option.
import os, string, sys
HEXCHARS = "0123456789abcdef"
hexdict = {}
for i in range(len(HEXCHARS)):
    hexdict[HEXCHARS[i]] = i
def convperc(filename):
    """ Tries to convert a filename with "%xx" in it to a filename with
        regular characters. 
    """
    newname, i = "", 0
    while i < len(filename)-2:
        c1, c2, c3 = filename[i], string.lower(filename[i+1]), \
          string.lower(filename[i+2])
        if c1 == "%" and c2 in HEXCHARS and c3 in HEXCHARS:
            value = 16 * hexdict[c2] + hexdict[c3]
            newname = newname + chr(value)
            i = i + 2
        else:
            newname = newname + c1
        i = i + 1
    newname = newname + filename[-2:]
    return newname
if __name__ == "__main__":
    def visit(arg, dirname, names):
        """ Function that renames all files in a directory. Can be called
            "solo" or with os.path.walk. 
        """
        print "---Checking %s...---" % dirname
        for filename in names:
            if "%" in filename:
                newname = convperc(filename)
                if filename != newname:
                    #print dirname+filename, "->", dirname+newname
                    os.rename(dirname+"/"+filename, dirname+"/"+newname)
                    print filename, "->", newname
    if "-s" in sys.argv[1:]:
        os.path.walk(".", visit, 1)
    else:
        filenames = os.listdir(".")
        visit(1, ".", filenames)