os.chdir() considered harmful

Daniel E. Wilson chronos at teleport.com
Sun Sep 24 22:05:28 EDT 2000


Guido van Rossum wrote:

> In a neat little piece of code posted by Tim, I found this gem:
>
> >         # This seems a little-known trick in Python:  changing to the
> >         # current directory allows the subsequent isdir-in-a-loop to
> >         # work on just the file name, instead of making the OS reparse
> >         # the whole darn path from the root again each time.
> >         # Depending on the OS, can save gobs of time.
>
> I have no objection to using this in a small self-contained program
> like Tim's example.  However I would like to warn that using
> os.chdir() is not always a safe practice!  The current directory is
> used for several purposes, like interpreting pathnames entered by the
> user, and importing Python modules supplied by the user.
> --Guido van Rossum (home page: http://www.pythonlabs.com/~guido/)

When I have to use os.chdir() I like to make sure that the old path is
restored when I am done.  So I use a class like this:

import os

class ChangePath:

  def __init__(self, newPath):
      self.savedPath = os.getcwd()
       os.chdir(newPath)

  def __del__(self):
      os.chdir(self.savedPath)

Then in a function I can simply create an instance which will last until
the function exits.  When the only reference to the instance is removed the
path is restored to the old path.  Needless to say I don't pass this
instance around so that the instance will be deleted when I expect.

I find this most useful when I have to walk a directory tree or work with
several files.  If Python ever decides to move away from reference counting
then I will have to think of something else.

--
Daniel E. Wilson

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






More information about the Python-list mailing list