| by Arround The Web | No comments

Python os.getcwd() Method | Explained With Examples

In Python, various modules are utilized such as os, pathlib, etc. to interact with the operating system. One such standard module named “OS” provides various methods and functions to interact with the operating system. This module performs different operations but getting the current working directory path is essential in Python. To retrieve the current/present working directory the “os.getcwd()” method of the “os” module is utilized in Python.

This blog post covers the following points via multiple examples:

What is the Python Current Working Directory?
What is the “os.getcwd()” Method in Python?

Alternative Method to Get Current Working Directory

Conclusion

What is the Python Current Working Directory?

In Python, the current working directory is the directory or folder where the Python script/program is executed. It can be different from the folder where the Python script is located, depending on how the script is executed. For instance, if you execute a Python program or script from the command line, the current working directory will be the same as the command line working directory. However, if you run a Python script from an IDE or file manager such as VScode, thonny, pycharm, etc. the current working directory may be different from the script locations.

What is the “os.getcwd()” Method in Python?

The “os.getcwd()” method of the “os” module retrieves the current/present working directory in Python. The current working directory is the location or path where the operation has been carried out. We can also change/modify the Python current/present working directory.

Syntax

os.getcwd()

 
Parameters

The “os.getcwd()” method of the “os” module does not take/accept any parameter.

Return Value

The “os.getcwd()” retrieves a string that includes the current/present working directory path. It retrieves the absolute path from the system’s root directory.

Before jumping to the example, let’s look at the following limitation of the Python “os.getcwd()” method:

    • The “getcwd()” method in Python only retrieves the current/present working directory. If you want the working directory path with the script name then use the “os.path.realpath()” method.
    • The “getcwd()” will not take any parameter but the “os.chdir()” while changing the directory will take the directory as an argument if not passed the “NotADirectoryError” returns.
    • The “FileNotFoundError” is retrieved while changing the directory if the input directory does not exist. Similarly, the “Permission Denied” error is retrieved if the specified directory requires permission.

Example 1: Retrieving Current Working Directory Using the “os.getcwd()” Method

In the first example, we initially imported the “os” module. After that, the “os.getcwd()” method retrieves the current working directory and stores it in a variable “dir1”. Lastly, the “print()” function shows the location of the current working directory.

import os
dir1 = os.getcwd()
print("Current Working Directory:", dir1)

 
The present working directory path is shown below:


Example 2: Create, Change, and Retrieving the Current Working Directory

In this example, we as usual import the “os” module at the start. Next, the “os.mkdir()” method of the os module is used to create the new directory named “new_directory”. After creating a new directory, we changed/modified the present working directory to the new directory utilizing the “os.chdir()” method. Lastly, the “os.getcwd() method is used to print the current working directory, which is the newly created directory.

import os
os.mkdir("new_directory")
os.chdir("new_directory")
print("Current Working Directory:" , os.getcwd())

 
The below output shows the current working directory:


Example 3: Create a File Without Specifying a Complete Path and Check the Directory

In this code block, we initially imported the “os” module. Next, we check the current working directory using the “os.getcwd()” method. After that, we created the file named “contents.txt” using the “open()” method. Next, we used the “os.path.realpath()” method of the “os” module to get the complete path of the current working directory along with the script name. This path displays that the new file is placed/located in the current/present working directory.

import os
print("Current Working Directory:")
print(os.getcwd())

fileName = "Contents.txt"
fileObject = open(fileName, "w+")
print("\nCreated File Full Path:")
print(os.path.realpath(fileName))

 
The above code displays the below output:

Alternative Method to Get Current Working Directory in Python

In Python, there are multiple other methods that can be employed to return the present working directory in Python. Some of the methods are the “pathlib.path.cwd()” method of the “pathlib” module, “os.path.realpath()” of the “os” module, and others. Let’s understand these methods by the following example:

Example 1: Get Current Working Directory Using “pathlib” Module

The example below shows the current working directory using the “pathlib” module. We first imported the “pathlib” module and got the location of the present working directory using the “pathlib.path.cwd()” method. Finally, the present working directory is displayed to the console output using the “print()” function.

import  pathlib
cwdir = pathlib.Path.cwd()
print("Current Working Directory Location:", cwdir)

 
The above code shows this to the console:


Example 2: Get Current Working Directory Using “realpath()” Method

We can also display the current/present working directory utilizing the “realpath()” method of the “os” module. In this example, we initially imported the “os” module. Next, the “os.path.realpath()” method takes the specified file name that is present in the current working directory to retrieve the absolute path. At the end, we print the current/present working directory to the console utilizing the print() function.

import os
cwdir = os.path.realpath('example1.txt')
print("Current Working Directory Including Script Name:\n")
print(cwdir)

 
The above code displays this to the console:

Conclusion

The “os.getcwd()” method of the “os” module is utilized to retrieve the current/present working directory path or location where the Python script is executed. We can also change/modify the present working directory of Python by utilizing the “os.chdir()” method. Alternative methods such as the “pathlib” module and the “os.path.realpath()” method can also be used to get the current working directory in Python. This guide delivered numerous examples and a detailed overview of the “os.getcwd()” method.

Share Button

Source: linuxhint.com

Leave a Reply