How to Set Current Working Directory in Python

0
37
How to Set Current Working Directory in Python

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.

Program

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()

Output

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.

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.