The Wayback Machine - https://web.archive.org/web/20240620111548/https://www.geeksforgeeks.org/python-os-chdir-method/
Open In App

Python os.chdir() method

Last Updated : 01 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 library
import os
 
# change the current directory
# to specified directory
os.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 module
import os
 
# change the current working directory
# to specified path
os.chdir('c:\\gfg_dir')
 
# verify the path using getcwd()
cwd = os.getcwd()
 
# print the current directory
print("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 libraries
import sys, os
 
# initial directory
cwd = os.getcwd()
 
# some non existing directory
fd = 'false_dir / temp'
 
# trying to insert to false directory
try:
    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


Previous Article
Next Article

Similar Reads

Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
4 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Python Dictionary get() Method
Python Dictionary get() Method return the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument). Python Dictionary get() Method Syntax: Syntax : Dict.get(key, default=None) Parameters: key: The key name of the item you want to return the value fromValue: (Optional) Value to
2 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | os._exit() 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._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buff
2 min read
Python | os.WEXITSTATUS() 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.WEXITSTATUS() method in Python is used to get the integer parameter used by a process in exit(2) system call if os.WIFEXITED(sta
3 min read
Practice Tags :