Extracting File Extensions in Python: A Comprehensive Guide
Determining the extension of a filename is essential in various programming scenarios. Python provides the os.path.splitext function to efficiently extract this file extension.
How to Extract File Extensions Using os.path.splitext?
To extract the file extension, simply import the os module and use os.path.splitext with the filename as its argument. This function returns a tuple containing two elements: the base filename (without the extension) and the file extension (including the leading dot).
import os filename = '/path/to/somefile.ext' filename, file_extension = os.path.splitext(filename) print(filename) # '/path/to/somefile' print(file_extension) # '.ext'
Advantages of Using os.path.splitext
os.path.splitext('/a/b.c/d') # ('/a/b.c/d', '') os.path.splitext('.bashrc') # ('.bashrc', '')
The above is the detailed content of How to Extract File Extensions in Python: Using os.path.splitext(). For more information, please follow other related articles on the PHP Chinese website!