How do you extract a filename without its extension from a file path in Python? | A1Lab@MZeeshanM to PythonEnglish • 6 days ago

How do you extract a filename without its extension from a file path in Python?

message-square
0

Use pathlib.Path(file_path).stem (the modern, cross-platform standard) or os.path.splitext(os.path.basename(file_path))[0] to strip the directory path and final file extension, returning just the base filename.

Basic Example

from pathlib import Path
import os

file_path = "/home/user/projects/quarterly_report.pdf"

# 1. Recommended (Python 3.4+): pathlib.Path.stem
filename_no_ext = Path(file_path).stem
print(filename_no_ext)  # Output: "quarterly_report"

# 2. Legacy / string-based alternative: os.path.splitext + os.path.basename
filename_no_ext_os = os.path.splitext(os.path.basename(file_path))[0]
print(filename_no_ext_os)  # Output: "quarterly_report"

Key Details & Edge Cases

  • Handling multi-part extensions (e.g., .tar.gz, .min.js): Both Path.stem and os.path.splitext() remove only the final suffix (Path("backup.tar.gz").stem returns "backup.tar"). To strip all extensions from a multi-extension filename, use Path.removesuffix() with Path.suffixes:
    p = Path("/backups/archive.tar.gz")
    clean_name = p.name.removesuffix("".join(p.suffixes))
    print(clean_name)  # Output: "archive"
    
  • Dotfiles without a secondary extension (e.g., .gitignore, .env): Both Path("/app/.gitignore").stem and os.path.splitext(".gitignore")[0] treat leading dots as part of the filename rather than an extension, returning ".gitignore" instead of an empty string "".
  • Files with no extension at all (e.g., Makefile, README): Path("/project/Makefile").stem safely returns "Makefile" without error.
  • Parsing Windows paths on Linux/macOS (PureWindowsPath): On Unix systems, Path(r"C:\docs\notes.txt") treats backslashes as literal filename characters. If your Linux/macOS service parses Windows path strings, use PureWindowsPath:
    from pathlib import PureWindowsPath
    
    print(PureWindowsPath(r"C:\docs\notes.txt").stem)  # Output: "notes"
    

Comparison of Filename-Without-Extension Methods

Method Example Input Output Multi-Extension (a.tar.gz) Best Used When
Path(p).stem "/dir/report.csv" "report" "a.tar" (strips last .gz) Modern Python 3.4+ codebases needing clean, readable path handling.
p.name.removesuffix("".join(p.suffixes)) "/dir/a.tar.gz" "a" "a" (strips all suffixes) Archives or versioned assets with compound extensions (.tar.bz2, .spec.ts).
PureWindowsPath(p).stem r"C:\dir\report.csv" "report" "a.tar" Parsing Windows path strings while running on Linux or macOS.
os.path.splitext(os.path.basename(p))[0] "/dir/report.csv" "report" "a.tar" Legacy scripts or performance-critical loops avoiding Path object instantiation.