Extract File Name from Path from Any OS/Path Format

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.

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.
Related

Python string does not have a built-in .contains() method like some other languages (e.g., Java), but you can easily check if a substring exists using…

10 Oct, 2025

These are the typical reasons why the conda command fails and practical steps to fix them across Windows, macOS and Linux environments. Here are some…

07 Oct, 2025

Hiring Python developers in the USA has become a top priority for companies building complex applications in finance, healthcare, e-commerce and enterprise technology. Companies are…

03 Oct, 2025
Request a Quote Schedule a Meeting