"cd" as in the shell command to change working directory ...
You can change the working directory with os.chdir( path ).
There are two best practices to follow:
- Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
- Return to your old directory when you're done. This is done in an exception-safe manner by wrapping your chdir call in a class:
class Chdir: def __init__( self, newPath ): self.savedPath = os.getcwd() os.chdir(newPath) def __del__( self ): os.chdir( self.savedPath )
Note that this snippet assumes that self.savedPath is still valid. Improving the handling of this is an exercise left up to the programmer.
Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.
I would use os.chdir
probably. It works like this:
os.chdir("/path/to/change/to")
By the way, if you need to figure out your current path, use os.getcwd()
.
More here: http://effbot.org/librarybook/os.htm
You probably already know this, but I'd like to remind people that if you change directory in a program, you won't be in that directory when the program exits and returns you to the shell.
If you're using a relatively new version of Python, you can also use a context manager, such as this one:
from __future__ import with_statement
from grizzled.os import working_directory
with working_directory(path_to_directory):
# code in here occurs within the directory
# code here is in the original directory
and for easy interactive use, ipython has all the common shell commands built in.