Skip to content

Instantly share code, notes, and snippets.

@samvv
Created February 14, 2025 20:33
Show Gist options
  • Select an option

  • Save samvv/20b89eff8fb502533dc49a3d8600bed3 to your computer and use it in GitHub Desktop.

Select an option

Save samvv/20b89eff8fb502533dc49a3d8600bed3 to your computer and use it in GitHub Desktop.
Current working directory as a resource in Python
with WorkDir("/foo/bar/baz"):
# Do something while inside /foo/bar/baz ...
pass
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