Learn how to extract file names from full paths in Python using os.path and pathlib. Works seamlessly on Windows, Linux, and macOS with no changes.
Scalable, Secure, and High-Performance Solutions for Your Business.
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.
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:
Also Read: Using Python For Data Science in 2025
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:
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.
eSparkBiz is rated 4.9 Stars
Real People, Real Stories
See why 300+ startups & enterprises trust eSparkBiz with their software outsourcingYou can copy files in python using the shutil module which provides high level file and collection of files operations. You can also combine it…
The demand for Python skills in Europe is growing as companies adopt AI driven solutions, enterprise platforms and interactive web applications. Businesses need developers who…
Amazon CloudWatch allows you to run log insights queries using the logs client in Boto3. Below is a step by step guide to querying logs…
Let’s discuss how our dedicated experts can help.