Python provides the chdir() method via the os module. The chdir() method is used to change the current working directory. The current working directory is used during command execution, directory, and file creation in order to use the default path. Command-line interfaces like bash, MS-DOS, PowerShell heavily use the current working directory for commands and function.
os.chdir() Method Syntax
The chdir() method is provided via the os module. The os module is installed by default for PYthon.
os.chdir(PATH)
- PATH is the path or location we want to change and set as new current working directory.
The os.chdir() method do not returns any value.
Change Current Working Directory
The current working directory can be changed by using the os.chdir(). We will provide the path we want to change as parameter. In the following example we will change the current working directory as “/home/ismail/Downloads”.
import os
os.chdir("/home/ismail/Downloads")
The chdir() method can be used in both Linux and Windows operating systems. So we can use the chdir() method to change current working directory into the “C:\Users\ismail”.
import os
os.chdir("/home/ismail/Downloads")
Print Current Working Directory
While changing the current working directory with the os.chdir() listing the current working directory is very important. The current working directory can be printed with the os.getcwd() method like below.
import os
os.getcwd()
os.chdir("/home/ismail/Downloads")
os.getcwd()
The output is like below.
'/home/ismail' '/home/ismail/Downloads'