What is the os.getcwd() method in Python?

Introduction

Getting the directory on which work is currently being done in a Python program is very essential. This can easily be achieved using the os.getcwd().

The Python scripting language comes with a lot of built in modules which make writing python much easier and fun nonetheless. One of such inbuilt modules is the OS module.

The OS module makes available different functions that are used to communicate with the operating system. This module is part of Python’s standard utility modules.

The os.getcwd() method is one of the functions which the OS module provides.

What is the os.getcwd() method?

The os.getcwd() method is used to get the current working directory of a process.

Somewhere in your script, you can add this function anytime you wish to know or get the directory of an operation currently being carried out.

Syntax

os.getcwd()

Parameters

This function takes no parameters.

Return value

Returns a string which stands for the current working directory. This can be saved in a variable and accessed when needed.

Example

# This program will return the CWD
# The os module is imported to enable use of os methods
import os
#This line gets the current working directory (CWD)
directory = os.getcwd()
# Output the current working directory (CWD) to screen
print("The Current working directory is :", directory)

Explanation

You can see from the output of the code above, the current directory of the code widget on this site was returned and printed to the output. This was achieved by:

  • First, on line 4 importing the os module so as to make its method available for use.
  • Next, calling the getcwd method of the os module and saving the return value which is the current working directory in a variable directory on line 8.
  • In the end, the last code line printed the value of variable directory to display.

Free Resources