How to get the absolute path of a file or directory in Python using os.path.abspath()?

Published on Aug. 22, 2023, 12:17 p.m.

To get the absolute path of a file or directory in Python, you can use the os.path.abspath() method. This method takes the path to the file or directory as its input and returns the absolute path as a string. Here is an example:

import os

path = "mydir/myfile.txt"
full_path = os.path.abspath(path)

print(full_path)

This will output something like:

C:/example/cwd/mydir/myfile.txt

In this example, os.path.abspath() returns the absolute path of the file located at path. Note that os.path.abspath() will also resolve any relative paths and normalize the path by removing any redundant separators or components.

Using os.path.abspath() is useful when you need to convert a relative path to an absolute path so that it can be used in functions or libraries that require an absolute path. Additionally, you can use os.path.abspath() to check whether a file or directory exists at a specific location on the file system.

Tags: