How to Get a File's Extension in Python with Path.suffix
A program that handles photos needs to tell a .jpg from a .txt before it opens anything. With pathlib you don't cut the name apart yourself: Path.suffix gives you the extension, dot included. This guide reads the extension of four file names on Python 3.15.2, including the awkward ones.
Syntax
Path("<file name or path>").suffix
| Part | What it means |
|---|---|
Path("<file name or path>") | The file, as a path. The file doesn't have to exist: suffix only reads the name |
.suffix | The extension: the last dot and what follows it, or an empty string when there is none |
The pathlib documentation defines it as "The last dot-separated portion of the final component, if any".
The Example
Four names: an ordinary photo, a file with a capitalised extension, a compressed archive with two extensions, and a file with none. A last line lists every extension of the archive.
Prerequisites
- uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
from pathlib import Path
for name in ["daisy.jpg", "notes.TXT", "archive.tar.gz", "README"]:
path = Path(name)
print(f"{name}: [{path.suffix}]")
print(Path("archive.tar.gz").suffixes)

The square brackets around the suffix show where it starts and ends, even when it's empty.
Step 2: Run It
uv run python suffixes.py
daisy.jpg: [.jpg]
notes.TXT: [.TXT]
archive.tar.gz: [.gz]
README: []
['.tar', '.gz']

What each line shows:
.jpg: the dot is part of the suffix..TXT: the suffix keeps its capital letters..gz: only the last extension.archive.tar.gzis a.tararchive compressed with gzip.[]:READMEhas no dot, so its suffix is an empty string.['.tar', '.gz']:suffixes, with an "s", lists every extension.
The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Comparing suffixes as they are | ".JPG" == ".jpg" is False, so a photo named IMG_01.JPG gets skipped | Compare path.suffix.lower() with lowercase extensions |
| Writing the extension without its dot | path.suffix == "jpg" is never true: the suffix is .jpg | Include the dot: ".jpg" |
Expecting .tar.gz from suffix | It gave .gz | Use suffixes, which gave ['.tar', '.gz'] |
FAQ
How do I get the name without the extension?
Use stem: for Path("photos/daisy.jpg"), name printed daisy.jpg and stem printed daisy.
Does the file have to exist?
No. suffix works on the name alone, so it works for files you are about to create too.
Conclusion
Path(name).suffix returned each file's last extension with its dot: .jpg, .TXT and .gz, and an empty string for README. Lowercase it before you compare, and use suffixes when you need every extension.
Additional Resources
- PurePath.suffix — the last extension.
- PurePath.suffixes — every extension.
- PurePath.stem — the name without its extension.
