# a context to change working directory # tested with python 2.6 and 3.1. For 2.5, uncomment this: # from __future__ import with_statement from contextlib import contextmanager import os @contextmanager def WorkingDirectory(dst_dir): dst_dir = os.path.abspath( os.path.normpath( os.path.expanduser( os.path.expandvars(dst_dir)))) current_dir = os.getcwd() os.chdir(dst_dir) try: yield dst_dir finally: os.chdir(current_dir) if __name__ == "__main__": # test code with WorkingDirectory(".."): # code in this with block is executed with # the parent dir as current working directory print(os.getcwd()) # after the with block, we are back in the # initial working directory. This is also # true if an exception is raised inside the with block. print(os.getcwd())
Are you able to help answer this sponsored question?
Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies.