Home >Backend Development >Python Tutorial >How to Extract File Extensions in Python?
Extracting File Extensions in Python
Extracting the file extension from a filename is a common task in programming. Python provides a convenient function, os.path.splitext, to handle this task effortlessly.
The os.path.splitext function takes a filename as an argument and returns a tuple containing two strings. The first string represents the filename without the extension, and the second string represents the extension itself.
For instance, if we provide the filename /path/to/somefile.ext to os.path.splitext, it will return:
>>> import os >>> filename = '/path/to/somefile.ext' >>> filename, file_extension = os.path.splitext(filename) >>> filename '/path/to/somefile' >>> file_extension '.ext'
Unlike manual string-splitting methods, os.path.splitext has several advantages:
>>> os.path.splitext('/a/b.c/d') ('/a/b.c/d', '')
>>> os.path.splitext('.bashrc') ('.bashrc', '')
By using os.path.splitext, we can easily extract file extensions in a reliable and efficient manner.
The above is the detailed content of How to Extract File Extensions in Python?. For more information, please follow other related articles on the PHP Chinese website!