Python › File I/O & Context Managers
How would you implement a context manager that temporarily changes the current working directory and restores it afterward?
AdvancedAnswer
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, guaranteedReal-world example Running a subprocess or script that requires a specific working directory, without permanently affecting the calling code's environment.