file_name_fixer.py

ewaguespack at gmail.com ewaguespack at gmail.com
Tue Jan 24 02:00:43 CET 2006


i put this together to fix a bunch of files with wierd names, please
gimme feedback, i am a newbie


#!/usr/bin/env python
import os
import sys
import string
import platform
dir = sys.argv[1]
noworky = sys.argv[2]
if platform.system() == 'Linux':
    uglychars = ''.join( set(string.punctuation+' ') - set('/_.') )
else:
    if platform.system() == 'Windows':#this is broken because windows
is gay with case
        uglychars = ''.join( set(string.punctuation+' ') -
set(':\\/_.') )
    else:
        print "wtf... what platform is this anyway?"
underscore = '_'
underscore = underscore * len(uglychars)
chars = string.maketrans(uglychars, underscore)
print "# PHASE I, DIRECTORIES"
for path, subdirs, files in os.walk(dir, topdown=True):
    oldname = path
    newname = oldname.translate(chars)
    newname = string.lower(newname)
    while string.count(newname, "__") > 0:
        newname = string.replace(newname,"__","_")
    while string.count(newname, "..") > 0:
        newname = string.replace(newname,"..",".")
    if oldname != newname:
        if os.path.isfile(newname) or os.path.isdir(newname):
            print oldname, "-->\n", newname, "\t\t\tERROR: file/dir
exists\n"
        else:
            print oldname, "-->\n", newname, "\t\t\tYAY: file
renamed\n"
            if noworky == "doit":
                os.renames(oldname, newname)
print "# PHASE II, FILES"
for path, subdirs, files in os.walk(dir, topdown=True):
    for oldname in files:
        oldname = os.path.join(path, oldname)
        newname = oldname.translate(chars)
        newname = string.lower(newname)
        newname = string.replace(newname,".mpeg",".mpg")
        newname = string.replace(newname,".ram",".rm")
        newname = string.replace(newname,".jpeg",".jpg")
        newname = string.replace(newname,".qt",".mov")
        while string.count(newname, "__") > 0:
            newname = string.replace(newname,"__","_")
        while string.count(newname, "..") > 0:
            newname = string.replace(newname,"..",".")
        newname = string.replace(newname,"._","_")
        newname = string.replace(newname,"_.",".")
        if oldname != newname:
            if os.path.isfile(newname) or os.path.isdir(newname):
                print oldname, "-->\n", newname, "\t\t\tERROR: file/dir
exists\n"
            else:
                print oldname, "-->\n", newname, "\t\t\tYAY: file
renamed\n"
                if noworky == "doit":
                    os.renames(oldname, newname)




More information about the Python-list mailing list