using functions and file renaming problem

Andy Jewell andy at wild-flower.co.uk
Fri Jul 18 14:28:15 CEST 2003


On Friday 18 Jul 2003 2:33 am, hokiegal99 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?

It almost is ;-)

> 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.

No, the problem is that you're throwing away all but the last correction.  
Read my comments below:

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)	# find any bad characters
         newfile = file
         for badchar in badchars:		# loop through each character in badchars  
         # note that if badchars is empty, this loop is not entered
             # show whats happening         
             print "replacing",badchar,"in",newfile,":", 
             # replace all occurrences of this badchar with '-' and remember 
             # it for next iteration of loop:            
             newfile = newfile.replace(badchar,'-') #replace bad chars.
             print newfile
         if badchars:	# were there any bad characters in the name?
             newpath = os.path.join(root,newfile)
             oldpath = os.path.join(root,file)
             os.rename(oldpath,newpath)
             print oldpath
print newpath
print " "
print "--- Done ---"
print " "


wrt wrapping it up in a function, here's a starter for you... "fill in the 
blanks":


-------8<-----------
def cleanup(setpath):
    # compile regex for finding bad characters

    # walk directory tree...

    # find any bad characters

    # loop through each character in badchars

             # replace all occurrences of this badchar with '-' and remember 

    # were there any bad characters in the name?

-------8<-----------

To call this you could do (on linux - mac paths are different):

-------8<-----------
cleanup("/home/andy/Python")
-------8<-----------

hope that helps
-andyj






More information about the Python-list mailing list