Python program to change the current working directory

Python program to change the current working directory:

In this post, we will learn how to change the current working directory in Python. Current working directory is the directory where currently the program is pointing to.

In Python, we have os module to work with different operating system related tasks. This is an inbuilt module of python and we can use it without installing any other third party libraries.

os module provides a method that can be used to change the current working directory to any other directory in Python.

os.chdir:

os.chdir method is used to change the current working directory.

It is defined as below:

os.chdir(path)

It takes one path, i.e. the new path to change the current working directory to this new path. It doesn’t return anything.

Python example program:

Below program shows how to change the current working directory in Python:

import os

new_directory = '/Users/cvc/'

print('Current working directory: {}'.format(os.getcwd()))

if os.path.exists(new_directory):
    os.chdir(new_directory)
    print('Changed to directory: {}'.format(os.getcwd()))
else:
    print('Invalid path')

Here,

  • new_directory is the new directory where we want to switch
  • Using os.getcwd(), we are printing the current working directory.
  • The if block checks if the new_directory actually exists or not. If it exists, it changes the current working directory to new_directory. Else, it prints one message that the path is invalid

If you run this program, it will print one output as like below :

Current working directory: /Users/cvc/Dropbox
Changed to directory: /Users/cvc

Exceptions:

If we provide one invalid directory to chdir, it will throw one FileNotFoundError.

FileNotFoundError: [Errno 2] No such file or directory:

We can wrap in in a try-except block to avoid this issue.

try:
    os.chdir(new_directory)
except FileNotFoundError:
    print('Error on changing directory')

You might also like: