How can I get the file extension from a filename in Python?

I’m working with files in Python and I need a way to extract the extension from a given filename. For example, if I have example.txt, I want to get "txt" as the result.

Is there a built-in function or a recommended approach to python get file extension?

Here’s a simple example of what I’m trying to achieve:

filename = "document.pdf"
# I want to extract "pdf" from this

What’s the cleanest and most reliable way to do this in Python, especially when filenames might contain multiple dots or no extension at all?

This is the method I use most often. It splits the filename into the root and the extension:

import os

filename = "document.pdf"
root, ext = os.path.splitext(filename)
print(ext)        # Output: '.pdf'
print(ext[1:])    # Output: 'pdf' (without the dot)

It’s safe even if the filename has multiple dots, like archive.tar.gz:

filename = "archive.tar.gz"
root, ext = os.path.splitext(filename)
print(ext)        # Output: '.gz'

Note that splitext only gives the last extension. If you need all parts, you might need extra handling.

I like this one for cleaner, object-oriented code:

from pathlib import Path

filename = Path("document.pdf")
print(filename.suffix)       # Output: '.pdf'
print(filename.suffix[1:])   # Output: 'pdf'

# For multiple extensions, use .suffixes
filename = Path("archive.tar.gz")
print(filename.suffixes)     # Output: ['.tar', '.gz']

This approach is especially nice if you’re already using pathlib for other file operations.

If you just want something simple and your filenames are well-formed:

filename = "document.pdf"
ext = filename.split('.')[-1]
print(ext)  # Output: 'pdf'

It works for most cases, but beware if the filename has no extension or starts with a dot (.gitignore).

Tip: I usually recommend os.path.splitext for compatibility or pathlib for modern Python code. They handle edge cases better than manual splitting.