HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How do I change the working directory in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
directoryhowtheworkingchangepython

Problem

cd is the shell command to change the working directory.
What is the equivalent in Python?

Solution

You can change the working directory with:
import os

os.chdir(path)


You should be careful that changing the directory may result in destructive changes your code applies in the new location. Potentially worse still, do not catch exceptions such as WindowsError and OSError after changing directory as that may mean destructive changes are applied in the old location!

If you're on Python 3.11 or newer, then consider using this context manager to ensure you return to the original working directory when you're done:
from contextlib import chdir

with chdir(path):
# do stuff here


If you're on an older version of Python, Brian M. Hunt's answer shows how to roll your own context manager: his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

Context

Stack Overflow Q#431684, score: 957

Revisions (0)

No revisions yet.