pythoncd

Equivalent of shell 'cd' command to change the working directory?


cd is the shell command to change the working directory.

How do I change the current working directory 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.