How to recursively walk directory & rename files & directories with Python 3.1 on windows?

#!c:/Python31/python.exe -u
import os

path = "test"
for (path, dirs, files) in os.walk(path):
    print (path)
    print ("-----------------")
    if "monitoring" in path:
        dst = path.replace("monitoring", "managing", 10)
        print (dst)
        os.rename(path, dst)
        print ("path----")
    for file in files:
        if "hw" in file:
            print (file)
            dst = file.replace("hw", "hw2", 10)
            os.rename(file, dst)
            print (dst)
            print ("file----")

My test program has this error:
Traceback (most recent call last):
File "C:\python\pathwalk.py", line 17, in <module>
os.rename(file, dst)
WindowsError: [Error 2] The system cannot find the file specified

You should avoid changing things in the course of the os.walk() call, as it stores information before it descends, and if you rename, you screw up the state. Instead, I'd use some kind of data structure to stash needed changes, then after returning from os.walk(), I'd do the renaming work. Not the most efficient possible, but it works.

By my thinking you are Ok to rename the files and directories can be renamed when the directory walking goes in one higher level go depth first in directories. So you can rename the files and do recursive renaming in subdirectories. Then last you can rename directories themselves.

By my thinking you are Ok to rename the files and directories can be renamed when the directory walking goes in one higher level go depth first in directories. So you can rename the files and do recursive renaming in subdirectories. Then last you can rename directories themselves.

Agree: If you know exactly how os.walk() works, you can call it so as to force depth first, and do the changes at the appropriate moment in the walk. I would do it that way if I needed maximum efficiency, and I'd write some tests to prove it was working as expected. For maximum clarity and to make things less brittle under maintenance, though, I would build a data structure holding the change details, then walk that structure after returning from os.walk(). (File system access isn't usually something that needs to be done with maximum efficiency.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.