Python os.path.basename() Method



The Python os.path.basename() method is used to get the base name of a path. The base name of a path is the last component of the path, which represents the filename or directory name without the directory part. It essentially returns the tail part of the path.

If the path ends with a directory separator (e.g., / on Unix-like systems or \ on Windows), the method returns an empty string, as there is no actual component following the separator. If the path is empty, the basename is '.' (referring to the current directory).

Syntax

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

os.path.basename(path)

Parameter

This method accepts a string as a parameter representing the path from which the filename component will be extracted.

Return Value

The method returns a string representing the filename component extracted from the given path.

Example

In the following example, we are extracting the filename "file.txt" from the file path "/home/lenovo/documents/file.txt" using the basename() method −

import os
file_path = "/home/lenovo/documents/file.txt"
filename = os.path.basename(file_path)
print("The file name obtained is:",filename)   

Output

The output obtained is as follows −

The file name obtained is: file.txt

Example

Here, we are extracting the filename "file.txt" from the Windows file path "C:\Users\user\Documents\file.txt" −

import os
file_path = "C:\\Users\\user\\Documents\\file.txt"
filename = os.path.basename(file_path)
print(filename)   

Output

Following is the output of the above code −

file.txt

Example

In this example, we are extracting the filename "file.txt" from the URL using the basename() method −

import os
url = "https://example.com/path/to/file.txt"
filename = os.path.basename(url)
print(filename)      

Output

The result produced is as shown below −

file.txt

Example

This example shows that if the path is empty, the basename() method returns an empty string as there is no component to extract −

import os
path = ""
result = os.path.basename(path)
print("The filename obtained is:",result)  

Output

We get the output as shown below −

The filename obtained is: 
os_path_methods.htm
Advertisements