What is the os.chdir() method in Python?

This os.chdir() method changes the current working directory to a specified path instance. It does not return any value.

This descriptor path must refer to the open directory, not to an open file.

Syntax

The syntax is given below:

os.chdir(path)

Parameters

path: This is the string as a directory or a path value.

Exception

The chdir() method may raise the following exceptions:

  • OSError: This exception is raised when a system-related error occurs.
  • FileNotFoundError: This exception is raised when a directory is requested but does not exist.
  • PermissionError: This occurs when accessing illegal memory or resources.

Explanation

Let’s discuss this method in detail:

# Demo code
import os
# Get current working directory
dirctory = os.getcwd()
print(f"Current directory: Before= {dirctory}")
# Path to chnage
path = '/usr/'
# Change current working directory
os.chdir(path)
# Get current working directory again
dirctory = os.getcwd()
print(f"Current working directory: After= {dirctory}")
  • Line 4 : We use the os.getcwd() method to extract the current working directory.
  • Line 7 : We see a temporary directory in the path variable as a string.
  • Line 9 : We use the chdir(path) method to change the current working directory.
  • Line 11: We again extract the current working dir to ensure change.

Free Resources