Advertisement
Advanced Python, File I/O & Context Managers

How would you implement a context manager that temporarily changes the current working directory and restores it afterward?

Short answer

Save the ORIGINAL working directory in __enter__ before changing to the new one, then restore it in __exit__ (or the equivalent finally block in a @contextmanager generator) — ensuring the change is always reverted even if an exception occurs while the directory is temporarily…

Save Python mock interview
Advertisement
AModel answer
Save the ORIGINAL working directory in __enter__ before changing to the new one, then restore it in __exit__ (or the equivalent finally block in a @contextmanager generator) — ensuring the change is always reverted even if an exception occurs while the directory is temporarily changed.
import os
from contextlib import contextmanager

@contextmanager
def temporary_directory(path):
    original = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(original)  # always restored, even on exception

with temporary_directory("/tmp"):
    process_files_here()
# working directory is back to the original, guaranteed
Real-world example
Running a subprocess or script that requires a specific working directory, without permanently affecting the calling code's environment.
Likely follow-ups
  • Why is this pattern particularly risky to implement WITHOUT a context manager, in terms of leaking the directory change on error?
Related topics