cd is the shell command to change the working directory.
How do I change the current working directory in Python?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can change the working directory with:
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
WindowsErrorandOSErrorafter 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:
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.