os.walk help

Robin Munn rmunn at pobox.com
Sat Nov 22 16:57:47 CET 2003


hokiegal99 <hokiegal99 at hotmail.com> wrote:
> 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

That's strange. It shouldn't be happening. Stick some print statements
in there and see what's going on:

> 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:
                  try:
>                    dirs.remove(dname)
                  except ValueError:
                     print "%s not in %s" % (dname, dirs)
                  else:
>                    dirs.append(newdname)
>                 newpath = os.path.join(root, newdname)
>                 oldpath = os.path.join(root, dname)
>                 os.renames(oldpath, newpath)

Note that I'm assuming it's the dirs.remove(dname) call that's
triggering the ValueError, since there aren't any invocations of
list.remove() anywhere else in your sample code. But I could be wrong;
you should look at the complete exception trace, which will include the
line number at which the exception was thrown.

-- 
Robin Munn
rmunn at pobox.com




More information about the Python-list mailing list