Python os.path.splitext() Method



The Python os.path.splitext() method is used to split a pathname into two parts: "root" and "ext". The "root" contains the filename without its extension, while "ext" holds the extension part of the filename, including the dot (.).

If the specified path does not have an extension, the extension part will be an empty string.

Syntax

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

os.path.splitext(path)

Parameter

This method accepts a string as a parameter representing the pathname that you want to split.

Return Value

The method returns a tuple containing the base part and the extension part of the specified path.

Example

In the following example, we are splitting the Windows path "C://Users//Lenovo//Desktop//file.txt" into its filename part and extension part using the splitext() method −

import os
path = "C://Users//Lenovo//Desktop//file.txt"
filename, extension = os.path.splitext(path)
print("Filename:", filename)
print("Extension:", extension)

Output

Following is the output of the above code −

Filename: C://Users//Lenovo//Desktop//file
Extension: .txt

Example

If the pathname has no extension, the splitext() method returns the entire pathname as the filename and an empty string as the extension −

import os
path = "C://Users//Lenovo//Desktop//file"
filename, extension = os.path.splitext(path)
print("Filename:", filename)
print("Extension:", extension)

Output

Output of the above code is as follows −

Filename: C://Users//Lenovo//Desktop//file
Extension:

Example

When we provide a filename containing multiple dots, the splitext() method considers the last dot as the separator between the filename and extension −

import os
path = "/home/lenovo/documents/file.tar.gz"
filename, extension = os.path.splitext(path)
print("Filename:", filename)
print("Extension:", extension)

Output

We get the output as shown below −

Filename: /home/lenovo/documents/file.tar
Extension: .gz

Example

This example shows that when the path is empty, both the filename and extension parts will be empty strings −

import os
path = ""
filename, extension = os.path.splitext(path)
print("Filename:", filename)
print("Extension:", extension)

Output

The result produced is as follows −

Filename: 
Extension:
os_path_methods.htm
Advertisements