Extracting extension from filename in Python

Better Stack Team
Updated on February 3, 2023

You can use the os.path.splitext() function from the os.path module in Python to extract the file extension from a filename.

Here's an example:

import os
filename = "example.txt"
extension = os.path.splitext(filename)[1]

This will output: .txt

Alternatively, you can use string slicing to extract the file extension.

import os
filename = "example.txt"
extension = filename[filename.index(".")+1:]

This will also output: .txt

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack