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

Steven D'Aprano steve at
Thu Mar 1 03:01:55 CET 2007

On Wed, 28 Feb 2007 08:38:41 +0100, Peter Otten wrote:

> Does the problem occur if you pass an absolute path to
> os.walk()/os.path.walk()?

Well, arguably the problem is that macunpack insists on writing to the
current working directory.

Or the problem is that os.walk sets the working directory to the initial
argument when you start, and then keeps it until it finishes. (Arguably
that's the right behaviour.)

You can play around with this to check:

def walker(where):
    """Walk through a directory tree, printing the current working directory."
    def _walk(data, dirname, files):
        print "dirname = '%s'; wd = '%s'" % (dirname, os.getcwd())
    os.path.walk(where, _walk, None)

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


Steven D'Aprano 

More information about the Python-list mailing list