Python program to change the current working directory:
In this post, we will learn how to change the current working directory in Python. The current working directory is the directory where currently the program is pointing to.
Python provides os
module to work with different operating system-related operations. This is an inbuilt module of Python. The os
module provides a method that can be used to change the current working directory to any other directory.
os.chdir
:
The os.chdir
method is used to change the current working directory.
It is defined as below:
os.chdir(path)
It takes one path
as the parameter. It will change the current working directory to this new path. It doesn’t return anything.
Python example program:
The below program shows how we can change the current working directory with os.chdir
:
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')
Download it on GitHub
Here,
new_directory
is the new directory where we want to switch.- By using the
os.getcwd()
method, we are printing the current working directory. - The
if
block checks if thenew_directory
actually exists or not. If it exists, it changes the current working directory tonew_directory
. Else, it prints one message that the path is invalid
If you run this program, it will print output as below :
Current working directory: /Users/cvc/Dropbox
Changed to directory: /Users/cvc
Exceptions:
If we provide one invalid directory path to the chdir
method, it will throw one FileNotFoundError
exception.
FileNotFoundError: [Errno 2] No such file or directory:
We can wrap it in a try-except
block to handle this.
try:
os.chdir(new_directory)
except FileNotFoundError:
print('Error on changing directory')
You might also like:
- Python os.path.lexists() method explanation with example
- How to check if a path is file or directory in Python
- How to get the last access time of a path in python
- Python program to get the last modified time of a path
- How to find the common path in a list of paths in python
- Python program to get the absolute path of a file
- How to get the directory name of a given path in Python