Skip to content

Instantly share code, notes, and snippets.

@j-faria
Created February 13, 2020 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j-faria/57d13047fe2153aee5c5057ae4c9dc39 to your computer and use it in GitHub Desktop.
Save j-faria/57d13047fe2153aee5c5057ae4c9dc39 to your computer and use it in GitHub Desktop.
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)
yield
os.chdir(prev_cwd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment