Python
08 Sep 2026
5 min read
Change Working Directories Safely with contextlib.chdir
Changing the current working directory is one of those operations that looks local in code but is global in effect. I still see scripts that call os.chdir(), do some work, and then try to remember where they started. Python 3.11 added contextlib.chdir(), which makes the restore step much cleaner. To be fair, though, a context manager does not make changing the working directory concurrency-safe. The important part is understanding what state is being changed and how long that state stays changed.