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. Here is a code snippet that demonstrates how to use it:

import os

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

Watch a course Python - The Practical Guide

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.

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 check if the current working directory is the same as the expected one using the os.path.exists() function.

import os

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