Python os.path.realpath() Method



The Python os.path.realpath() method is used to retrieve the canonical path of a specified filename. It resolves any symbolic links or relative path components in the provided path and returns the absolute path to the file or directory.

A canonical path, also known as an absolute path, refers to the unique and unambiguous representation of the location of a file or directory within a file system. It specifies the complete path from the root directory to the target file or directory without any symbolic links, relative path components, or redundant elements.

Syntax

Following is the basic syntax of the Python os.path.realpath() method −

os.path.realpath(path)

Parameter

This method accepts a string as a parameter representing the filename for which you want to obtain the canonical path.

Return Value

The method returns a string representing the canonical path of the specified filename.

Example

In the following example, we are resolving the path "C://Users//Lenovo//Desktop//file.txt" to its canonical form using the realpath() method −

import os
path = "C://Users//Lenovo//Desktop//file.txt"
real_path = os.path.realpath(path)
print("Real Path:", real_path)  

Output

Following is the output of the above code −

Real Path: C:\Users\Lenovo\Desktop\file.txt

Example

Here, we are resolving a relative path to its canonical form using the realpath() method −

import os
relative_path = "../OS Module HTML Files/file.txt"
real_path = os.path.realpath(relative_path)
print("Real Path:", real_path)

Output

Output of the above code is as shown below −

Real Path: C:\Users\Lenovo\OS Module HTML Files\file.txt

Example

This example shows resolving a path with environment variable expansion to its canonical form −

import os
env_path = "$HOME/file.txt"
real_path = os.path.realpath(os.path.expandvars(env_path))
print("Real Path:", real_path)

Output

We get the output as shown below −

Real Path: C:\Users\Lenovo\file.txt

Example

Now, we are resolving a relative path based on the current working directory using the realpath() method −

import os
relative_path = "OS Module HTML Files/file.txt"
os.chdir("C://Users//Lenovo//Desktop")
real_path = os.path.realpath(relative_path)
print("Real Path:", real_path) 

Output

The result produced is as follows −

Real Path: C:\Users\Lenovo\Desktop\OS Module HTML Files\file.txt
os_path_methods.htm
Advertisements