Change the current working Directory in Python
In this tutorial, we will learn about how to change the current working directory in Python with some easily understandable examples.
When we are dealing with Python in some cases we are required to change the current working directory in Python.
We will see how to do the above specified in the following tutorial.
Without any further delay let us start our tutorial.
Changing the current directory in Python
Before starting let us see what is a directory in Python.
Directory: A directory in Python is a collection of files. we can also have subdirectories under a directory.
In order to change the current working dictionary in Python, we use a method in the “OS module”.
OS module: This is used for the purpose of communicating with the operating system. This module comes along with the Python so we need not download/install it externally.
OS module contains many methods that are useful in handling the directories.
path: The path of the directory for which we want to change the path.
we use the dot “.” operator to call the chdir method.
This method does not return any value.
# Python code to change path of the current working Directory import os def current_path(): print("Path of current working directory before") print(os.getcwd()) print() current_path() os.chdir('../') print("Path of current working directory after") current_path()
Current working directory before C:\Users\C.SuryaVenkat\Documents Current working directory after C:\Users\C.SuryaVenkat\Desktop
In the above example, as we can see before using the “chdir” method the path was” C:\Users\C.SuryaVenkat\Documents ” but after calling the chdir method the path is changed to “C:\Users\C.SuryaVenkat\Desktop”.
By following the above procedure we can change the path of the directory.
When we give the invalid/incorrect path then it raises “OSError”. So we must be careful while specifying the path.
Finally, I am hoping that this tutorial is helpful for you in understanding about how to change the current working directory in Python.
You can also read: