Python os.chdir() method

Usage

The os.chdir() method, short for “change directory”, changes the current working directory (CWD) to a specified path.

This method is analogous to the cd command used in both Unix-based systems (like Linux and macOS) and Windows.

Syntax

os.chdir(path)

Parameters

Python os.chdir() method parameters
ParameterConditionDescription
pathRequiredA path to the directory you want to switch to, which can be absolute or relative.

Return Value

os.chdir() does not return any value. It changes the current working directory to the specified path. If the operation is successful, the script’s execution continues from the new directory.

If the function fails because the specified path does not exist or the process does not have the necessary permissions to change the directory, it raises a FileNotFoundError or a PermissionError, respectively.

Example 1: Changing to a Directory Using an Absolute Path

Absolute paths specify a location from the root directory down to the target directory. For example, C:\Users\YourUserName\Documents is an absolute path. All of the information needed to locate the file is contained in the path string.

The code below changes the current working directory to the specified directory using an absolute path:

import os

# Change the current working directory
absolute_path = "C:\\Users\\YourUserName\\Documents"
os.chdir(absolute_path)

Example 2: Changing to a Directory Using a Relative Path

You can also change the current working directory using a relative path. A relative path refers to a location that is relative to a current directory.

The example below changes the current working directory to the ‘Scripts’ directory, which is located directly inside the current working directory.

import os

# Change the current working directory
# Assuming there's a directory named 'Scripts' in the current working directory
relative_path = "Scripts"
os.chdir(relative_path)

Example 3: Navigating to a Parent Directory

You can use .. to move up one level in the directory tree.

import os

# Move up one directory from the current working directory
os.chdir('..')
print("Moved up to:", os.getcwd())

Example 4: Handling Exceptions

The os.chdir() function can raise the following exceptions:

  • FileNotFoundError: Raised if the specified directory does not exist.
  • PermissionError: Raised if the process lacks the necessary permissions to access the directory.

Therefore, it is recommended to encapsulate os.chdir() within a try-except block to handle potential errors gracefully.

import os

# Specify the absolute path to the target directory
path = '/path/to/your/target/directory'

try:
    os.chdir(path)
except FileNotFoundError:
    print("Error: The specified path does not exist.")
except PermissionError:
    print("Error: Permission denied to change to the specified directory.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")