using functions and file renaming problem

Bengt Richter bokr at oz.net
Fri Jul 18 00:08:32 EDT 2003


On Thu, 17 Jul 2003 21:33:42 -0400, hokiegal99 <hokiegal99 at hotmail.com> wrote:

>A few questions about the following code. How would I "wrap" this in a 
>function, and do I need to?
>
>Also, how can I make the code smart enough to realize that when a file 
>has 2 or more bad charcters in it, that the code needs to run until all 
>bad characters are gone? For example, if a file has the name 
>"<bad*mac\file" the program has to run 3 times to get all three bad 
>chars out of the file name.
>
>The passes look like this:
>
>1. <bad*mac\file becomes -bad*mac\file
>2. -bad*mac\file becomes -bad-mac\file
>3. -bad-mac\file becomes -bad-mac-file
>
>I think the problem is that once the program finds a bad char in a 
>filename it replaces it with a dash, which creates a new filename that 
>wasn't present when the program first ran, thus it has to run again to 
>see the new filename.
Maybe I'm misunderstanding, but in a previous post I suggested combining the
name transformations before even going to the file system for renaming. E.g,
if you have
    lessbadfilename = fixup1(badfilename); rename(badfilename,lessbadfilename)
    evenlessbadfilename = fixup2(lessbadfilename); rename(lessbadfilename,evenlessbadfilename)
    okfilename = fixup3(evenlessbadfilename); rename(evenlessbadfilename,okfilename)
why bother with all the renames, when you could do a single one at the end, i.e.,
    rename(badfilename, okfilename)
i.e., why record the intermediate names in the file system, only to change them?

>
>import os, re, string
>bad = re.compile(r'%2f|%25|[*?<>/\|\\]') #search for these.
>print " "
>setpath = raw_input("Path to the dir that you would like to clean: ")
>print " "
>print "--- Remove Bad Charaters From Filenames ---"
>print " "
>for root, dirs, files in os.walk(setpath):
>     for file in files:
>         badchars = bad.findall(file)
>         newfile = ''
>         for badchar in badchars:
>             newfile = file.replace(badchar,'-') #replace bad chars.
>         if newfile:
>             newpath = os.path.join(root,newfile)
>             oldpath = os.path.join(root,file)
>             os.rename(oldpath,newpath)
>	    print oldpath
>	    print newpath
>print " "
>print "--- Done ---"
>print " "
>
This looks like an old post that ignores some responses you got to your original post like this.
Did some mail get lost? Or was this an accidental repost of something old? I still see
indentation misalignments, probably due to mixing tabs and spaces (bad news in python ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list