Home >Backend Development >Python Tutorial >How to Extract File Extensions in Python?

How to Extract File Extensions in Python?

DDD
DDDOriginal
2024-11-16 17:44:03516browse

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:

  • It correctly handles cases where the filename does not have an extension, such as /a/b.c/d:
>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
  • It also handles cases where the filename starts with a dot, such as .bashrc:
>>> 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn