Python Glossary Русский

Python 3.11+contextlibterm

contextlib.chdir

managers

A context manager that temporarily changes the current working directory (3.11+).

Syntax

with contextlib.chdir(path): ...

It changes the working directory of the whole process, not of one thread, so in threaded or async code other threads and tasks suddenly see someone else's directory — the docs call it out as not thread-safe. Nesting is fine, though: it is reentrant and remembers the previous directory on each entry. In everyday code building absolute paths is safer; keep chdir for third-party code that insists on operating relative to the current directory.

Examples

import contextlib
import os
cm = contextlib.chdir('.')
print(hasattr(cm, '__enter__') and hasattr(cm, '__exit__'))   # → True
with contextlib.chdir('.') as v: print(v)   # → None
before = os.getcwd()
with contextlib.chdir('..'): print(os.getcwd() == os.path.dirname(before))   # → True
print(os.getcwd() == before)   # → True
with contextlib.chdir('no_such_dir'): pass   # → FileNotFoundError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy