Created
May 9, 2014 14:42
-
-
Save vsudilov/c851b91886d67d436749 to your computer and use it in GitHub Desktop.
Change directory context (python)
This file contains hidden or 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
| class cd: | |
| """ | |
| Context manager for changing the current working directory | |
| with cd('/path'): | |
| open('file_in_path') | |
| """ | |
| def __init__(self, newPath): | |
| self.newPath = newPath | |
| def __enter__(self): | |
| self.savedPath = os.getcwd() | |
| os.chdir(self.newPath) | |
| def __exit__(self, etype, value, traceback): | |
| os.chdir(self.savedPath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Functional version:
Note that in Python3.11 this function is included as
contextlib.chdir.