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.

Summarize with AI

Not enough time? get the key points instantly.

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

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

Worth Reading

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.


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

Python

How to Copy Files in Python

You can copy files in python using the shutil module which provides high level file and collection of files operations. You can also combine it…