Skip to content

Instantly share code, notes, and snippets.

@vsudilov
Created May 9, 2014 14:42
Show Gist options
  • Select an option

  • Save vsudilov/c851b91886d67d436749 to your computer and use it in GitHub Desktop.

Select an option

Save vsudilov/c851b91886d67d436749 to your computer and use it in GitHub Desktop.
Change directory context (python)
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)
@mondeja

mondeja commented May 26, 2022

Copy link
Copy Markdown

Functional version:

import os
import contextlib

@contextlib.contextmanager
def cd(new_path):
    old_cwd = os.getcwd()
    os.chdir(new_path)
    yield
    os.chdir(old_cwd)

Note that in Python3.11 this function is included as contextlib.chdir.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment