In Python, you can extract just the filename from a full path using either
os.path.basename() or
pathlib.Path().name. Both methods are cross-platform, meaning they work on Windows, Linux, and macOS without modification.
Method 1: Using os.path.basename()
Returns the final part of any path string, stripping directories before the file.
import os# Linux/macOS style path
unix_path = "/home/user/documents/report.pdf"
print(os.path.basename(unix_path)) # Output: report.pdf
# Windows style path
windows_path = "C:\\Users\\Admin\\Desktop\\notes.txt"
print(os.path.basename(windows_path)) # Output: notes.txt
Explanation:
- Windows uses backslashes (\) in its file paths
- Linux/macOS use forward slashes (/)
- Python handles both formats automatically with os.path.
Also Read: Using Python For Data Science in 2025
Method 2: Using pathlib.Path().name
A modern, object-oriented approach that works with both forward
/ and backward
\ slashes.
from pathlib import Path
# macOS/Linux-style path
unix_path = Path("/Users/alex/Desktop/image.png")
print(unix_path.name) # Output: image.png
# Windows-style path (raw string recommended)
windows_path = Path(r"C:\Users\Admin\Documents\report.docx")
print(windows_path.name) # Output: report.docx
Explanation:
- Using Path().name automatically extracts the last component (file name) from any path, regardless of OS.
- Prefix Windows-style paths with r"" to prevent escape sequence errors (e.g., \n, \t).
Tip
Always use pathlib for new projects—it’s cross-platform, more intuitive than os.path, and handles both Windows and Unix-style paths out of the box.