Skip to content

Instantly share code, notes, and snippets.

@amitkot
Last active July 26, 2016 18:14
Show Gist options
  • Save amitkot/b85f20903f877055ff72 to your computer and use it in GitHub Desktop.
Save amitkot/b85f20903f877055ff72 to your computer and use it in GitHub Desktop.
Python Context Manager for change directory (source - http://code.activestate.com/recipes/576620-changedirectory-context-manager/)
import contextlib
import os
@contextlib.contextmanager
def working_directory(path):
"""A context manager which changes the working directory to the given
path, and then changes it back to its previous value on exit.
"""
prev_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(prev_cwd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment