Use the pathlib module to extract extension from file in Python. The pathlib module to get the file extension. Pathlib.Path(“/Users/pankaj/abc.txt”).suffix returns .txt.
The os.path module has a splitext() function to split the file path into root and extension. This function splits the file path string into the file name and extension into a pair of root and extension. The splitext() function returns a tuple having two values – root and extension. import os file_name, file_extension = os.path.splitext(“/Users/Username/abc.txt”).
Being able to work with files in Python easily is the language’s strength. You can use the glob library to iterate over files in a folder. Knowing the file extension may drive decisions. So knowing how to get a file’s extension is important.
On Windows, right-click the file, select Open with, and choose another app to open different file types. If solutions don’t help open the file, double-check the extension.
Among these solutions, os.path.splitext stands out to get file extension in Python. It assists in extracting the extension of a given file. Syntax: os.path.splitext(filepath) where filepath is the path. It returns a tuple – first element is the path without the last period, second element is the extension from the last period.