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

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Feb 28 00:21:13 EST 2007


On Tue, 27 Feb 2007 20:31:43 -0800, Scott David Daniels wrote:

>>     def findallfiles(self, base):
>>         self.results = []
>>         for root,dirs,files in os.walk(base):
>>             os.chdir(root)
>        ^^^ Mistake here, don't change directories during os.walk ^^^

I came across this problem some time ago. I had to walk a directory tree,
calling an external program on each file. Unfortunately, that external
program wrote directly to the current working directory, which caused all
sorts of havoc. This is how I dealt with it:


def unbin(where):
    """Walk through a directory tree, calling macunpack to extract the
    contents of MacBinary files.
    """
    def _unbin(data, dirname, files):
        for oldname in files:
            fullname = os.path.normpath(os.path.join(dirname, oldname))
            if os.path.isfile(fullname):
                # Dammit, macunpack writes directly to the current 
                # working directory. Changing the cwd breaks the file
                # tree walker, so we have to remember the current 
                # directory, change it to where we want to be, then
                # change it back.
                wd = os.getcwd()
                os.chdir(dirname)
                result = os.system('macunpack -f "%s"' % oldname)
                if result == 0:
                    # Unpacking worked, so delete the original.
                    os.remove(oldname)
                os.chdir(wd) # sigh...
        
    os.path.walk(where, _unbin, None)


Is there another (better) way of dealing with this sort of situation?


-- 
Steven D'Aprano 




More information about the Python-list mailing list