Created
February 14, 2025 20:33
-
-
Save samvv/20b89eff8fb502533dc49a3d8600bed3 to your computer and use it in GitHub Desktop.
Current working directory as a resource in 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
| with WorkDir("/foo/bar/baz"): | |
| # Do something while inside /foo/bar/baz ... | |
| pass |
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
| import os | |
| from pathlib import Path | |
| class WorkDir: | |
| def __init__(self, path: Path): | |
| self.new_dir = path | |
| self.old_dir = None | |
| def __enter__(self): | |
| self.old_dir = os.getcwd() | |
| os.chdir(self.new_dir) | |
| return self | |
| def __exit__(self, exc_type, exc_val, exc_tb): | |
| os.chdir(cast(Path, self.old_dir)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment