Fetch and Modify the Present Working Directory using Python

In Python, you have the option to access and alter the present working directory by utilizing os.getcwd() and os.chdir(). These functions are included in the standard library’s os module, ensuring their availability without the need for supplementary installations; however, you must remember to import the module.

Get the current working directory: os.getcwd()

os.getcwd() method returns a string which represents the current working directory.

“getcwd” is a shorthand for “get current working directory,” while the Unix command “pwd” is an acronym for “print working directory.” To display the current working directory in Python, you can simply use os.getcwd() and then print the result using the print() function.

import os

path = os.getcwd()

print(path)
# C:\Program Files\Python

print(type(path))
# <class 'str'>

Change the current working directory: os.chdir()

You can change or set the current working directory using os.chdir() method.

Provide the desired path as an argument, which can be either an absolute or relative path. You can utilize ‘../’ to navigate up one level in the directory structure.

The function os.chdir() is responsible for altering the current directory, akin to the Unix command ‘cd,’ where both ‘chdir’ and ‘cd’ are abbreviations for ‘change directory.

# import os module
import os

# change to a directory one level up from current directory
os.chdir('../')

print(os.getcwd())
# C:\Program Files

Change to different working directory :

# import os module
import os
 
# change the current working directory to a specified path
os.chdir('c:\\Spark')
 
# verify the path using getcwd()
cwd = os.getcwd()
 
# print the current directory
print("Current working directory is:", cwd)

Output:

Current working directory is: c:\Spark