os.chdir() considered harmful

Daniel E. Wilson chronos at teleport.com
Mon Sep 25 22:55:52 CEST 2000

Rob Hooft wrote:

>  DEW> When I have to use os.chdir() I like to make sure that the old path is
>  DEW> restored when I am done.  So I use a class like this:
>  DEW> import os
>  DEW> class ChangePath:
>  DEW>   def __init__(self, newPath):
>  DEW>     self.savedPath = os.getcwd()
>  DEW>     os.chdir(newPath)
>  DEW>   def __del__(self):
>  DEW>     os.chdir(self.savedPath)
> You better make sure that only one of these is active at any time, or
> that they get destroyed in reverse order of creation!

That why I only use it in a function.  The function call semantics act like a
stack which is the behavior I want.  As long as I keep only one reference to an
instance in a local variable then this works.  This code will also fail when
threads are used.
Keeping a reference to a ChangePath instance at the module level or using a
global variable would also cause this code to fail.

This class is simply a way for me to simplify the code in a function that works
with several files in a directory.

Daniel E. Wilson

The perversity of the Universe tends towards a maximum.
        -- Larry Niven

More information about the Python-list mailing list