In this article we will discuss how to change the current working directory in python.

Current working directory is the directory in which program is running.

Change Current Working Directory in Python

First of all we need to import python’s os module i.e.

import os

Python’s os module provides a function to change the current working directory i.e.
os.chdir(path)

It changes the current working directory to the given path.

Let’s understand by an example,

First print the current working directory using os.getcwd() i.e.

print("Current Working Directory " , os.getcwd())

Now let’s change the current working directory using os.chdir(path) i.e.
os.chdir("/home/varun/temp")

If the given path don’t exist then os.chdir() with throw error : FileNotFoundError. Therefore we should either call it using try / except i.e.
try:
    # Change the current working Directory    
    os.chdir("/home/varun/temp")
    print("Directory changed")
except OSError:
    print("Can't change the Current Working Directory")        

or check if the new directory exists before changing the working directory i.e.
# Check if New path exists
if os.path.exists("/home/varun/temp") :
    # Change the current working Directory    
    os.chdir("/home/varun/temp")
else:
    print("Can't change the Current Working Directory")    

Complete example is as follows,
import os

def main():
    
    print("Current Working Directory " , os.getcwd())
    
    
    try:
        # Change the current working Directory    
        os.chdir("/home/varun/temp")
        print("Directory changed")
    except OSError:
        print("Can't change the Current Working Directory")        

    print("Current Working Directory " , os.getcwd())
    
    # Check if New path exists
    if os.path.exists("/home/varun/temp") :
        # Change the current working Directory    
        os.chdir("/home/varun/temp")
    else:
        print("Can't change the Current Working Directory")    

        
    
    print("Current Working Directory " , os.getcwd())
    
if __name__ == '__main__':
    main()


Output:
Current Working Directory  /home/varun/Documents/blog/pythonSamples/FileSamples
Directory changed
Current Working Directory  /home/varun/temp
Current Working Directory  /home/varun/temp

 

Join a list of 2000+ Programmers for latest Tips & Tutorials