os.walk help
hokiegal99
hokiegal99 at hotmail.com
Sun Nov 23 12:47:30 EST 2003
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.
Robin Munn wrote:
> 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.
>
More information about the Python-list
mailing list