Created
January 26, 2016 01:42
-
-
Save nottrobin/3d675653244f8814838a to your computer and use it in GitHub Desktop.
Change directory / working directory context processor for python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from contextlib import contextmanager | |
@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. | |
Usage: | |
> # Do something in original directory | |
> with working_directory('/my/new/path'): | |
> # Do something in new directory | |
> # Back to old directory | |
""" | |
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