Change Current Working Directory In Python

Python provides different file and directory-related functions. While working with Python we may need to change the current working directory. Even we generally first check the current working directory and then change the current working directory accordingly. The os.chdir() method is used to change the current directory. In this tutorial, we examine how to change the current working directory in different ways like using absolute path, relative path, parent directory, or root directory.

Display Current Working Directory

It is very useful to get the current working directory before changing it or after changing it. We can use the os.getcwd() method in order to return the current working directory. In the following example first, we import the os module which provides the “getcwd()” method. We execute the getcwd() method and assign the current working directory into the cwd variable and print it to the console.

import os

cwd = os.getcwd()

print("Current working directory is ",cwd)
Current working directory is  /home/ismail

Change Current Working Directory

The os.chdir() method is used to change the current working directory. The method name chdir() comes from “change directory”. We provide the new path or directory to the chdir() method as a parameter. In the following example, we change the current working directory into “/var/log”. We can see that the “/var/log” is a full or absolute path which is generally better than the relative path.

import os

print(os.getcwd())

os.chdir("/var/log")

print(os.getcwd())
/home/ismail
/var/log

Change Current Working Directory with Relative Path

We can change the current working directory by providing a relative path. We can just change to the sibling directory child directory using the relative path. In the following example, we navigate to the sibling directory “ismail” and its child directories “db” and “backup”.

import os

print(os.getcwd())

os.chdir("ismail/db/backup")

print(os.getcwd())

Change To Parent Directory

We can change to the parent directory by using the os.chdir() command. We can use the .. in order to change to the parent directory.

import os

print(os.getcwd())

os.chdir("..")

print(os.getcwd())
/home/ismail
/home

Change To Root Directory

We can change the root directory in the Linux systems by using the os.chdir() method. The root directory is expressed as / .

import os

os.chdir("/")

Leave a Comment