Change language

Python | os.chdir () method

|

os.chdir() in Python is used to change the current working directory to the specified path. Only one argument is required as the 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 directory

# Python3 program to modify
# file directory using os.chdir () method

 
# OS library import

import os

  
# change current directory
# to the specified directory 

os.chdir (r "C: UsersGfgDesktopgeeks" )

  

print ( "Directory changed" )

Exit :

 Directory changed 

Code # 2: Using os.getcwd ()
To find out the current working directory of a file, you can use the getcwd () method. After changing the path using this method, you can check the path to the current working directory.

# import module os

import os

 
# change the current working directory
# to the specified path

os.chdir ( ’c: gfg_dir’ )

 
# change path with getcwd ()

cwd = os.getcwd ()

 
# print the current directory

print ( "Current working directory is:" , cwd)

Exit:

 Current working directory is: c:  gfg_dir 

Code # 3: Handling errors when changing directory

# import all required libraries

import sys, os

 
# home directory

cwd = os.getcwd ()

 
# some nonexistent directory

fd = ’false_dir / temp’ < / p>

 
# trying to insert into the flase directory

try :

os.chdir (fd)

  print ( " Inserting inside- " , os.getcwd ())

 
# Exception caching

except :

print ("Something wrong with specified

  directory. Exception - ", sys.exc_info ())

  
# processing from finally

finally :

print ( " Restoring the path " )

  os.chdir (cwd)

  print ( " Current directory is- " , os. getcwd ())

Output:

 Inserting inside- c: gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c: gfg_dirgfg 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method