How can I do "cd" in Python?

You can change the current working directory in Python using the os.chdir() function from the os module. This function is equivalent to the cd command in terminal/command prompt.

Syntax

os.chdir(path)

Parameters:

  • path − A string representing the absolute or relative path of the directory you want to switch to

Basic Example

Here's how to change to a subdirectory ?

import os

# Get current directory
print("Current directory:", os.getcwd())

# Change to a subdirectory (create it first for demo)
os.makedirs('my_folder', exist_ok=True)
os.chdir('my_folder')

# Verify the change
print("New directory:", os.getcwd())
Current directory: /home/user
New directory: /home/user/my_folder

Using Absolute Paths

You can also use absolute paths to navigate to any directory ?

import os

# Get current directory
print("Current directory:", os.getcwd())

# Change to root directory (Unix/Linux/Mac)
# On Windows, use: os.chdir('C:\')
os.chdir('/')

print("Changed to:", os.getcwd())
Current directory: /home/user/my_folder
Changed to: /

Going Back to Parent Directory

Use .. to move up one directory level ?

import os

# Create a nested directory structure for demo
os.makedirs('parent/child', exist_ok=True)
os.chdir('parent/child')
print("Current directory:", os.getcwd())

# Go back to parent directory
os.chdir('..')
print("After cd ..:", os.getcwd())

# Go back to grandparent
os.chdir('..')
print("After another cd ..:", os.getcwd())
Current directory: /home/user/parent/child
After cd ..: /home/user/parent
After another cd ..: /home/user

Error Handling

Always handle potential errors when changing directories ?

import os

try:
    os.chdir('nonexistent_folder')
    print("Directory changed successfully")
except FileNotFoundError:
    print("Directory not found!")
except PermissionError:
    print("Permission denied!")
Directory not found!

Key Points

  • os.chdir() changes the current working directory for the entire Python process
  • Use os.getcwd() to get the current working directory
  • Relative paths are relative to the current directory
  • Always handle FileNotFoundError and PermissionError exceptions

Conclusion

Use os.chdir() to change directories in Python, just like the cd command in terminal. Always wrap it in try-except blocks to handle errors gracefully.

Updated on: 2026-03-24T17:22:42+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements