W3docs

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

In Python, you can use the os module to change the current working directory using the chdir() function.

In Python, you can use the os module to change the current working directory using the chdir() function. Here is a code snippet that demonstrates how to use it:

os.chdir as the equivalent of shell cd command in Python

import os

# Change the current working directory to '/path/to/directory'
os.chdir('/path/to/directory')

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use the os.getcwd() function to get the current working directory, and os.path.abspath() to get the absolute path of a file or directory.

os.getcwd() and os.path.abspath() for path resolution in Python

import os

# Get the current working directory
print(os.getcwd())

# Get the absolute path of a file or directory
print(os.path.abspath('path/to/file'))

You can verify that a target path is a valid directory before changing to it using the os.path.isdir() function.

Verify and change the working directory in Python

import os

if os.path.isdir('/path/to/directory'):
    os.chdir('/path/to/directory')
    print("Changed working directory to ", os.getcwd())
else:
    print("Directory does not exist")