How to Extract File Extensions in Python?

DDD
Release: 2024-11-16 17:44:03
Original
441 people have browsed it

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'
Copy after login

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', '')
Copy after login
  • It also handles cases where the filename starts with a dot, such as .bashrc:
>>> os.path.splitext('.bashrc')
('.bashrc', '')
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template