os.walk help
hokiegal99
hokiegal99 at hotmail.com
Fri Nov 21 19:36:16 EST 2003
Joe Francia wrote:
> Your code is trying to recurse into the list of directories in 'dirs',
> but you are renaming these directories before it can get to them. For
> example, if dirs = ['baddir?*', 'gooddir', 'okdir'], you rename
> 'baddir?*' to 'baddir--' and then os.walk tries to enter 'baddir?*' and
> cannot find it. You're better off building a list of paths to rename,
> and then renaming them outside of the os.walk scope, or doing something
> like...
>
> dirs.remove(dname)
> dirs.append(newdname)
>
> ...in your 'if' block.
>
> Peace,
> Joe
So, which is better... rename in the os.walk scope or not? The below
code works sometimes at others it produces this error:
ValueError: list.remove(x): x is not in list
setpath = raw_input("Path to the Directory: ")
def clean_names(setpath):
bad = re.compile(r'%2f|%25|%20|[*?<>/\|\\]')
for root, dirs, files in os.walk(setpath):
for dname in dirs:
badchars = bad.findall(dname)
for badchar in badchars:
newdname = dname.replace(badchar,'-')
if newdname != dname:
dirs.remove(dname)
dirs.append(newdname)
newpath = os.path.join(root, newdname)
oldpath = os.path.join(root, dname)
os.renames(oldpath, newpath)
More information about the Python-list
mailing list