@contextlib.contextmanager<EOL>def chdir(dirname=None):
curdir = os.getcwd()<EOL>try:<EOL><INDENT>if dirname is not None:<EOL><INDENT>os.chdir(dirname)<EOL><DEDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>os.chdir(curdir)<EOL><DEDENT>
This context manager restores the value of the current working directory
(cwd) after the enclosed code block completes or raises an exception.  If a
directory name is supplied to the context manager then the cwd is changed
prior to running the code block.

Shamelessly lifted from
http://www.astropython.org/snippet/2009/10/chdir-context-manager