os.walk help

Joe Francia usenet at soraia.com
Fri Nov 21 17:40:48 EST 2003


hokieghal99 wrote:
> This script is not recursive... in order to make it recursive, I have to 
> call it several times (my kludge... hey, it works). I thought os.walk's 
> sole purpose was to recursively walk a directory structure, no? Also,it 
> generates the below error during the os.renames section, but the odd 
> thing is that it actually renames the files before saying it can't find 
> them. Any ideas are welcomed. If I'm doing something *really* wrong 
> here, just let me know.
> 
> #-------------- ERROR Message ----------------------#
> 
>   File "/home/rbt/fix-names-1.1.py", line 29, in ?
>     clean_names(setpath)
>   File "/home/rbt/fix-names-1.1.py", line 27, in clean_names
>     os.renames(oldpath, newpath)
>   File "/usr/local/lib/python2.3/os.py", line 196, in renames
>     rename(old, new)
> OSError: [Errno 2] No such file or directory
> 
> #------------- Code -------------------------#
> 
> setpath = raw_input("Path to the Directory: ")
> bad = re.compile(r'[*?<>/\|\\]')
> 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:
>             newpath = os.path.join(root, newdname)
>             oldpath = os.path.join(root, dname)
>             os.renames(oldpath, newpath)
> 

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




More information about the Python-list mailing list