Use Path(filename).suffix from Python’s built-in pathlib module (or os.path.splitext(filename)[1]) to extract the final extension including its leading dot (e.g., ".csv"), or use "".join(Path(filename).suffixes) when you need compound multi-part extensions like ".tar.gz".
Basic Example
import os
from pathlib import Path
filename = "/var/backups/archive_2026.tar.gz"
# 1. Recommended (modern Python 3.4+): Path.suffix returns the final extension with dot
ext = Path(filename).suffix
print(ext) # Output: ".gz"
print(ext.lstrip(".")) # Output: "gz" (without leading dot)
# 2. Extract ALL compound suffixes for multi-dot archives (.tar.gz, .min.js)
all_exts = "".join(Path(filename).suffixes)
print(all_exts) # Output: ".tar.gz"
# 3. Classic string-path alternative: os.path.splitext() -> (root, ext)
root, ext_os = os.path.splitext("report.PDF")
print(ext_os.lower()) # Output: ".pdf" (normalize case for reliable comparisons)
Key Details & Edge Cases
- Hidden dotfiles without an extension (
.gitignore,.env,.bashrc):- Both
Path(".gitignore").suffixandos.path.splitext(".gitignore")[1]treat a single leading dot on a filename as a hidden file prefix rather than an extension—returning""(an empty string) instead of".gitignore". - However, a hidden file with an extension (
.config.json) returns".json"as expected.
- Both
- Files with no extension (
"Makefile","README","/path.with.dots/file"):- Both
Path.suffixandos.path.splitext()inspect only the final path component (Path.name)—dots in parent directory names (/v1.2/) are safely ignored, and files with no extension return"".
- Both
- Trailing dot edge case (
"file."):Path("file.").suffixreturns""(empty string), whereasos.path.splitext("file.")[1]returns"."(a single dot).
- Case sensitivity across operating systems (
.JPGvs..jpg):- Both functions preserve the original filename’s casing (
".JPG"). Always normalize with.lower()(Path(p).suffix.lower() in {".jpg", ".jpeg", ".png"}) when validating allowed file types so uppercase camera/Windows extensions match reliably.
- Both functions preserve the original filename’s casing (
- Extracting the filename without its extension (
Path.stem):- Pair
Path(p).suffixwithPath(p).stem("archive_2026.tar") when you need the base filename without its final extension—orfilename.removesuffix("".join(Path(p).suffixes))to strip compound extensions cleanly.
- Pair
Comparison of File Extension Extraction Methods in Python
| Method | Module | Input "/dir.v1/data.tar.gz" |
Input ".env" |
Best Used When |
|---|---|---|---|---|
Path(p).suffix |
pathlib |
".gz" |
"" |
Standard single-extension extraction in modern object-oriented Python code. |
"".join(Path(p).suffixes) |
pathlib |
".tar.gz" |
"" |
Handling multi-part archive or versioned extensions (.tar.gz, .tar.bz2). |
os.path.splitext(p)[1] |
os.path |
".gz" |
"" |
Legacy codebases or tight loops processing raw string paths without Path instantiation. |
Path(p).suffix.lstrip(".") |
pathlib |
"gz" |
"" |
Passing format names without a leading dot (e.g., to Pillow Image.save(..., format=...)). |
You must log in or register to comment.
