os.chdir() considered harmful

Clarence Gardner clarence at netlojix.com
Sun Sep 24 19:04:49 EDT 2000


On Sun, 24 Sep 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.

Also, one must always be careful, when walking through directories,
whether using chdir() or not, to be mindful of what the current directory
is, and whether the a path you're holding in your hand is valid from that
root.  I didn't test this, but I'm pretty sure from inspection that Tim's
function only works if the original function is passed an absolute path.




More information about the Python-list mailing list