There are times when you have to process information being stored in different directories through your Python based applications. Being rich in features, the Python computer programming language comes with all the utilities one needs to interact with the functionalities provided by the operating system.
Through this tutorial, we are going to look at a practical example which focuses on how one can use the os module to change the current working directory.
First of all, make sure to open a Python interactive shell so you can run the commands and see the results by yourself.
What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.
Once you have managed to open a Python interactive console on your own operating system, use the Python import statement to get the os module in your session. The syntax for achieving such thing is shown below.
import os
Recommended for you: Get network issues from WhatsUp Gold. Not end users.
Then assign the absolute path of the directory which you want to navigate to a variable like shown below.
# define the path of the directory in here
path = ‘/Users/oltjano/Desktop/Test’
Then use the command shown below to navigate to the directory you want to.
os.chdir(path)
According to the official documentation, the os.chdir utility is being used to change the current working directory. It takes the path of the directory as an argument.
Final thoughts
The Python builtin os module comes with all the features and utilities the Python coder needs to interact with the operating system and its functionalities. Through this article, we learned a practical example on how the Python geek can utilize the os.chdir utility to change the current working directory.