os.walk help

Peter Otten __peter__ at web.de
Mon Nov 24 14:23:07 EST 2003


Robin Munn wrote:

> hokiegal99 <hokiegal99 at hotmail.com> wrote:
>> Thanks for the tip. That code shows all of the dirs that Python is
>> complaining about not in the list... trouble is, they *are* in the list.
>> Go figure. I'd like to try doing the rename outside the scope of
>> os.walk, but I don't undersdtand how to do this, when I break out of
>> os.walk and try the rename at a parallel level, Python complains that
>> variables such as "oldpath" and "newpath" are undefined.
> 
> 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:

Here's a way to modify the list while iterating over it. Too lazy to
generate the sample directory tree, so I suggest that the OP test it :-)

<untested>
def clean_names(rootpath):
    bad = re.compile(r'%2f|%25|%20|[*?<>/\|\\]')
    for root, dirs, files in os.walk(rootpath):
        for index, dname in enumerate(dirs):
            newdname = bad.sub('-', dname)
            if newdname != dname:
                newpath = os.path.join(root, newdname)
                oldpath = os.path.join(root, dname)
                try:
                    os.rename(oldpath, newpath)
                except OSError:
                    print >> sys.stderr, "cannot rename %r to %r" %
(oldpath, newpath)
                else:
                    dirs[index] = newdname # inform os.walk() about the new
name
</untested>

Peter




More information about the Python-list mailing list