How to Use the Python os.path.abspath() Method

09/17/2021

Contents

In this article, you will learn how to use the Python os.path.abspath() method.

Python os.path.abspath() Method

The os.path.abspath() method in Python is used to return the absolute path of a file or directory. An absolute path refers to the complete path from the root directory to the file or directory. Here’s how to use the os.path.abspath() method in Python:

Import the os module:

import os

Use the os.path.abspath() method and pass the path of the file or directory whose absolute path you want to obtain:

path = os.path.abspath("file.txt")

The above code will return the absolute path of the file named “file.txt” in the current working directory.

Alternatively, you can use a relative path to the file or directory and os.path.abspath() will convert it to an absolute path:

path = os.path.abspath("../file.txt")

This will return the absolute path of the file named “file.txt” located in the parent directory of the current working directory.

Print the absolute path:

print(path)

This will print the absolute path of the file or directory.

Note that os.path.abspath() does not check whether the file or directory actually exists, it simply returns the absolute path.