Python os.path.abspath() method is used to get the normalized absolute path of a specified file or directory. In simple terms, it turns a relative path into an absolute path.
If the given path is relative, this method considers it relative to the current working directory.
The abspath() method normalizes the path, which resolves symbolic links, relative paths (. and ..), and redundant separators.
Syntax
os.path.abspath(path)
Parameters
Name | Description |
path (string, required) | It is a path or file name as a parameter representing a file system path. |
Return Value
It returns a normalized version of the pathname path.
Example 1: Getting the Absolute Path of a Relative Path
Let’s say we have a file called “new.txt” inside our current working directory:
import os
relative_path = 'new.txt'
absolute_path = os.path.abspath(relative_path)
print(absolute_path)
Output
/Users/krunallathiya/Desktop/Code/pythonenv/env/new.txt
Example 2: Absolute Path of a Directory
Let’s get the absolute path of the “dir” directory:
import os
relative_path = './dir'
absolute_path = os.path.abspath(relative_path)
print(absolute_path) # Outputs the absolute path of the 'dir' directory
Output
/Users/krunallathiya/Desktop/Code/pythonenv/env/dir
Example 3: Absolute path with Normalization
import os
relative_path = '../dir/new.txt'
absolute_path = os.path.abspath(relative_path)
print(absolute_path)
Output
/Users/krunallathiya/Desktop/Code/pythonenv/dir/new.txt
In this code example, the method resolves the .. component in the relative path and provides the absolute path to new.txt in dir.