using functions and file renaming problem
hokiegal99
hokiegal99 at hotmail.com
Thu Jul 17 21:33:42 EDT 2003
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.
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 " "
More information about the Python-list
mailing list