How do you extract the file extension from a filename in Python? | A1Lab@MZeeshanM to PythonEnglish •
edit-2
4 days ago

How do you extract the file extension from a filename in Python?

message-square
0

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").suffix and os.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.
  • Files with no extension ("Makefile", "README", "/path.with.dots/file"):
    • Both Path.suffix and os.path.splitext() inspect only the final path component (Path.name)—dots in parent directory names (/v1.2/data) are safely ignored, and files with no extension return "".
  • Trailing dot edge case ("file."):
    • Path("file.").suffix returns "" (empty string), whereas os.path.splitext("file.")[1] returns "." (a single dot).
  • Case sensitivity across operating systems (.JPG vs. .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.
  • Extracting the filename without its extension (Path.stem):
    • Pair Path(p).suffix with Path(p).stem ("archive_2026.tar") when you need the base filename without its final extension—or filename.removesuffix("".join(Path(p).suffixes)) to strip compound extensions cleanly.

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=...)).