Python

How to Get Current Working Directory in Python

The file or folder name can be used with the full path or just mentioning the file or folder name only to use it in the script. The full path of a file or folder from the root directory is specified by absolute path. When the file name is used without the pathname in the script, then the Current Working Directory is assumed as the file’s pathname and is called the relative path. In Python, the Current Working Directory is set to the directory location from where the python script executes. Many modules exist in python to get the Current Working Directory. The ways to retrieve the Current Working Directory by using different modules in Python have shown in this tutorial.

Example-1: Using pathlib module to get Current Working Directory

The path class of the pathlib module is used to read the current working directory of the executing script. Create a python script with the following code to read and print the current working directory using the pathlib module. The cwd() method of the Path class is used to print the current working directory from where the script is executing.

# Import the Path from pathlib module

from pathlib import Path

# Retrieve the path of current working directory

current_working_directory = Path.cwd()

# Print the location of current working directory

print("The location of the current working directory is:")

print(current_working_directory)

Output:

The following output will appear after executing the above script. Here, the path of the current working directory without the script name has shown in the output.

Example-2: Using normpath() and abspath() to get the Current Working Directory

Using the os module is another way to retrieve the current working directory. Different methods exist in the path class of the os module to retrieve the current working directory. The normpath() and abspath() methods are the two of them. These methods return the current working directory as a string. Create a python file with the following script to check the purposes of these functions.

# Import os module

import os

# Print the current working directory using normpath() function

print("The current working directory (using normpath()) is:")

print(os.path.dirname(os.path.normpath(__file__)))

# Print the current working directory using abspath() function

print("\nThe current working directory (using abspath()) is:")

print(os.path.abspath('.'))

Output:

The following output will appear after executing the above script. Here, the path of the current working directory without the script name has shown in the output.

Example-3: Using realpath() to get the Current Working Directory

The realpath() is another method to retrieve the current working directory. Create a python file with the following script to print the current working directory with the script name by using the realpath() method. In the script, it takes the __file__ as the argument value containing the file’s pathname in which the os module is imported.

# Import os module

import os

# Read the current working directory using realpath() function

real_path = os.path.realpath(__file__)

# Print the current working directory with the script name

print("\nThe current working directory with the script name is:")

print(real_path)

Output:

The following output will appear after executing the above script. Here, the path of the current working directory with the script name has shown in the output.

Example-4: Using getcwd() to get the Current Working Directory

Using the getcwd() function of the os module is the most simple way to retrieve the current working directory of the executing script. It does not contain any argument and returns the CWD as a string. Create a python file with the following script to check the use of the getcwd() function. The current working directory is printed at the beginning of the script. Next, the current directory path is changed by using the chdir() function. The getcwd() command is called again after changing the directory.

# Import os module

import os

# Print the current working directory using getcwd() function

print("The current working directory is:\n", os.getcwd())

# Change the current working directory

os.chdir('/etc/mail')

# Print the current working directory after change

print("\nThe current working directory after change is:\n", os.getcwd())

Output:

The following output will appear after executing the above script. Here, the current working directory path without the script name has been printed before changing the directory. Next, the changed directory path has been printed.

Example-5: Using getcwd() with try-except to get the Current Working Directory

Create a python file with the following script to change the current working directory based on the input value and handle different types of errors. Three types of errors can be handled by executing the script. The FileNotFoundError error will be generated if the path taken from the input does not exist. The NotADirectoryError error will be generated if the path taken from the input is not a directory. The PermissionError error will be generated if the path taken from the input is not accessible.

# Import the os module

import os

# Enter the path of the directory

cwd = input("Enter the path of current working directory:\n")


try:

    # Change the current working directory

    os.chdir(cwd)

    # Print the current working directory using getcwd() function

    print("The current working directory is:\n", os.getcwd())

# Raise error if the directory does not exist

except FileNotFoundError:

    print("Directory does not exist.")

# Raise error if the input path is not a directory

except NotADirectoryError:

    print("%s is not a directory" %(cwd))

# Raise error if the directory is not accessible

except PermissionError:

    print("Permission denied to change the directory.")

Output:

The following output will appear after executing the above script if the path exists. Here, the taken input path exists, and the changed working directory has printed in the output.


The following output will appear after executing the above script if the path does not exist.


The following output will appear after executing the above script if the taken path is not accessible.

Conclusion:

The use of pathlib and os modules to read the current working directory is shown in this tutorial by using different examples. The way to retrieve the current working directory after changing the current working directory based on user input has also been shown in this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.