Use pathlib.Path(file_path).name (to get the filename including its extension) or pathlib.Path(file_path).stem (to get the filename without its extension)—as pathlib handles both POSIX forward slashes (/) and Windows backslashes (\) natively across operating systems.
Basic Example
from pathlib import Path
# Works seamlessly with both POSIX (/) and Windows (\) paths
posix_path = "/home/user/documents/report_2026.pdf"
win_path = r"C:\Users\Alice\Desktop\archive.tar.gz"
# 1. Extract the full filename (including extension)
print(Path(posix_path).name) # Output: "report_2026.pdf"
print(Path(win_path).name) # Output: "archive.tar.gz"
# 2. Extract the filename without the final extension (.stem)
print(Path(posix_path).stem) # Output: "report_2026"
print(Path(win_path).stem) # Output: "archive.tar"
Key Details & Edge Cases
- Parsing foreign OS paths on a different OS (
PureWindowsPath/PurePosixPath): On Linux or macOS,Path(r"C:\folder\file.txt")treats backslashes as literal filename characters rather than directory separators because the host OS is POSIX. If your script runs on Linux/macOS and parses Windows path strings (e.g., from uploaded files or logs), usePureWindowsPath:from pathlib import PureWindowsPath print(PureWindowsPath(r"C:\Users\Alice\data.csv").name) # Output: "data.csv" - Stripping multiple extensions (e.g.,
.tar.gz):Path("archive.tar.gz").stemonly removes the last suffix (.gz), returning"archive.tar". To strip all suffixes cleanly:p = Path("archive.tar.gz") base_name = p.name.removesuffix("".join(p.suffixes)) print(base_name) # Output: "archive" - Trailing slashes on directory paths: Unlike the Unix
basenamecommand (which strips trailing slashes) oros.path.basename("/a/b/")(which returns""),Path("/a/b/").nameautomatically normalizes trailing slashes and returns"b". - Legacy
os.pathalternative (os.path.basename/os.path.splitext): When working with older codebases that expect plainstrpaths instead ofPathobjects, useos.path.basename(path)for the full filename andos.path.splitext(os.path.basename(path))[0]for the name without extension.
Comparison of Path Filename Extraction Methods
| Method / Property | Example Input | Output | Handles Trailing /? |
Best Used When |
|---|---|---|---|---|
Path(p).name |
"/dir/photo.jpg" |
"photo.jpg" |
Yes (Path("/dir/").name → "dir") |
Modern Python 3.4+ code needing the full filename. |
Path(p).stem |
"/dir/photo.jpg" |
"photo" |
Yes | Getting the filename without its final extension. |
PureWindowsPath(p).name |
r"C:\dir\photo.jpg" |
"photo.jpg" |
Yes | Parsing Windows paths while running on Linux or macOS. |
os.path.basename(p) |
"/dir/photo.jpg" |
"photo.jpg" |
No (os.path.basename("/dir/") → "") |
Legacy scripts or APIs requiring raw string manipulation without Path. |
You must log in or register to comment.
