os.walk help
hokiegal99
hokiegal99 at hotmail.com
Mon Nov 24 15:31:02 EST 2003
This works great! No errors... and it gets dirs that are 8 levels deep
(that's as far down as I've tested). Thanks for the tip! The re.sub
seems to be much faster than the string find/replace approach as well...
I need to read-up more on the documentation of os.walk and re in
general. Thanks again!!!
Robin Munn wrote:
> Wait, I just realized that you're changing the list *while* you're
> iterating over it. That's a bad idea. See the warning at the bottom of
> this page in the language reference:
>
> http://www.python.org/doc/current/ref/for.html
>
> Instead of modifying the list while you're looping over it, use the
> topdown argument to os.walk to build the tree from the bottom up instead
> of from the top down. That way you won't have to futz with the dirnames
> list at all:
>
> def clean_names(rootpath):
> bad = re.compile(r'%2f|%25|%20|[*?<>/\|\\]')
> for root, dirs, files in os.walk(rootpath, topdown=False):
> for dname in dirs:
> newdname = re.sub(bad, '-', dname)
> if newdname != dname:
> newpath = os.path.join(root, newdname)
> oldpath = os.path.join(root, dname)
> os.renames(oldpath, newpath)
>
> Notice also the use of re.sub to do all the character substitutions at
> once. Your code as written would have failed on a filename like "foo*?",
> since it always renamed from the original filename: it would have first
> done os.renames("foo*?", "foo-?") followed by os.renames("foo*?",
> "foo--") and the second would have raised an OSError.
>
More information about the Python-list
mailing list