The python os.chdir(path)
function changes the Current Working Directory. It takes only a single argument as new directory path.
os.chdir Syntax
The syntax of the os.chdir(path)
method is as follows:
os.chdir(path)
os.chdir Parameters
path
: A complete path of directory to be changed to new directory path.
os.chdir Returns
The python os.chdir(path)
function doesn’t return any value.
os.chdir Demo #1: Basic usage of os.chdir
#!/usr/bin/python3
import os
cwd = os.getcwd()
print("Current working directory is:", cwd)
# change the current directory to specified directory
os.chdir(r"C:\Users\hp\Desktop\apimemos")
# verify the path using getcwd()
cwd = os.getcwd()
print("Current working directory is:", cwd)
When we run above program, it produces following result −
Current working directory is: D:\Tool\ITTranslate
Current working directory is: C:\Users\hp\Desktop\apimemos
os.chdir Demo #2: Handling the exceptions when changing the directory
#!/usr/bin/python3
import os
import sys
# initial directory
print("Current directory is:", os.getcwd())
# non-existing directory
non_existing_dir = 'false_dir / apidemos/'
# try to move to non-existing directory
try:
os.chdir(non_existing_dir)
print("Change directory with no exceptions, Current directory is:", os.getcwd())
except:
print("os.chdir to", non_existing_dir, " with exception:", sys.exc_info())
finally:
print("Current directory is:", os.getcwd())
When we run above program, it produces following result −
Current directory is: D:\Tool\ITTranslate
os.chdir to false_dir / apidemos/ with exception: (<class 'FileNotFoundError'>, FileNotFoundError(2, 'The system cannot find the path specified'), <traceback object at 0x0000021EB8276D00>)
Current directory is: D:\Tool\ITTranslate