os.chdir() method is used to change the current working directory to a specified directory path. After changing the directory, all relative file and folder operations are performed from the new location.
Example: In the code below, we change the current working directory and then display the updated directory path.
import os
os.chdir("Documents")
print(os.getcwd())
Output
C:\Users\User\Documents
Explanation: os.chdir("Documents") changes the current working directory to the Documents folder. os.getcwd() then displays the updated directory path.
Syntax
os.chdir(path)
- Parameters:
path- The directory path to switch to. It can be an absolute path or a relative path. - Returns: This method does not return any value.
Examples
Example 1: In the code below, we change the current working directory using an absolute path and verify the change.
import os
os.chdir(r"C:\Users\User\Documents")
print(os.getcwd())
Output
C:\Users\User\Documents
Explanation: os.chdir() changes the current directory to the path provided, and os.getcwd() returns the new directory path.
Example 2: In the code below, we move one level up from the current directory using a relative path.
import os
os.chdir("..")
print(os.getcwd())
Output
C:\Users\User
Explanation: ".." represents the parent directory. os.chdir("..") moves the current working directory one level up.
Example 3: In the code below, we store the current directory, switch to another directory, and then return to the original directory.
import os
old_dir = os.getcwd()
os.chdir("Documents")
print("Current:", os.getcwd())
os.chdir(old_dir)
print("Restored:", os.getcwd())
Output
Current: C:\Users\User\Documents
Restored: C:\Users\User
Explanation: old_dir = os.getcwd() stores the current directory. Later, os.chdir(old_dir) restores the original working directory.