import os import contextlib @contextlib.contextmanager def new_cd(x): d = os.getcwd() # This could raise an exception, but it's probably # best to let it propagate and let the caller # deal with it, since they requested x os.chdir(x) try: yield finally: # This could also raise an exception, but you *really* # aren't equipped to figure out what went wrong if the # old working directory can't be restored. os.chdir(d)