Changing directories in oswalk [was Re: Walk thru each subdirectory from a top directory]

Peter Otten __peter__ at web.de
Fri Mar 2 04:33:12 EST 2007


Steven D'Aprano wrote:

> For those times when os.walk's behaviour doesn't mesh well with that of
> the external program you are calling (like macunpack) is there an
> alternative to:
> 
> - save the cwd;
> - change directories;
> - call the program;
> - return to the saved directory
> 
> ?

os.walk() creates paths from the root you provide and the files/direcotories
it finds via os.listdir(), and uses that to determine. If that root is an
absolute path any such paths are absolute, too, and undoing the directory
change is not necessary.

cwd = os.getcwd()
for path, dirs, files in os.walk(os.path.abspath(root)):
    os.chdir(path)
    for file in files:
        invoke external program
os.chdir(cwd)

That said, undoing the change immediately is better style, and probably a
good usecase for a with statement like

with current_working_directory(path):
    invoke external program

Last minute idea:

for path, dirs, files in os.walk(root):
    for file in files:
        os.system("cd '%s' && macunpack '%s'" % (path, file))

Peter




More information about the Python-list mailing list