Python os.chdir() method
OS module in Python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path.
Syntax: os.chdir(path)
Parameters:
path: A complete path of directory to be changed to new directory path.
Returns: Doesn’t return any value
Code #1: Use chdir() to change the directory
Python3
# Python3 program to change the# directory of file using os.chdir() method# import os libraryimport os# change the current directory# to specified directoryos.chdir(r"C:\Users\Gfg\Desktop\geeks")print("Directory changed") |
Output:
Directory changed
Code #2: Use of os.getcwd()
To know the current working directory of the file, getcwd() method can be used. After changing the path, one can verify the path of current working directory using this method.
Python3
# import os moduleimport os# change the current working directory# to specified pathos.chdir('c:\\gfg_dir')# varify the path using getcwd()cwd = os.getcwd()# print the current directoryprint("Current working directory is:", cwd) |
Output:
Current working directory is: c:\\gfg_dir
Code #3: Handling the errors while changing the directory
Python3
# importing all necessary librariesimport sys, os# initial directorycwd = os.getcwd()# some non existing directoryfd = 'false_dir / temp'# trying to insert to false directorytry: os.chdir(fd) print("Inserting inside-", os.getcwd()) # Caching the exception except: print("Something wrong with specified\ directory. Exception- ", sys.exc_info()) # handling with finally finally: print("Restoring the path") os.chdir(cwd) print("Current directory is-", os.getcwd()) |
Output:
Inserting inside- c:\gfg_dir\gfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:\gfg_dir\gfg
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.

