You often change the current working directory if you are working with multiple projects.
What is the current working directory in Python?
A working directory is a current directory in which you write a script and run a script file. To work with file and folder systems, an OS module is typically used in Python to manage and modify files and folders.
How to set the current working directory in Python
To set the current working directory in Python, use the os.chdir() method. The os.chdir() is a built-in Python function that changes the current working directory to the given path. It returns None in all the other cases.
The chdir() method changes the current working directory to the provided path. It takes one argument as a new directory path.
import os def current_working_dir(): print("Current working directory") print(os.getcwd(), "\n") current_working_dir() os.chdir("../../") print("After setting a new current directory", "\n") current_working_dir()
Current working directory /Users/krunallathiya/Desktop/Code/R After setting a new current directory Current working directory /Users/krunallathiya/Desktop/
In this example, we are first printing the current path in which this code file is located.
Then, using the os.chdir() function, we set the current path to a 2-level lower path.
Use the os.getcwd() function first, which shows the format of the accepted input for the os.chdir() function.