Python
path manipulation
os module
string processing
programming tutorials

How to get only the last part of a path in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

To get the last part of a path in Python, use a path-aware library instead of splitting strings manually. The usual modern answer is pathlib.Path(path).name, while os.path.basename is still common in older code and works well if you understand its trailing-separator behavior.

The Cleanest Modern Option: pathlib

pathlib gives a clear object-oriented API for path handling.

python
1from pathlib import Path
2
3path = Path("/var/log/app/server.log")
4print(path.name)   # server.log

This returns the final path component, which is often what people mean by “the last part of the path.”

It also works naturally with relative paths:

python
from pathlib import Path

print(Path("reports/2026/summary.csv").name)   # summary.csv

The Older Equivalent: os.path.basename

If your codebase already uses os.path, basename is the direct equivalent.

python
import os

print(os.path.basename("/var/log/app/server.log"))  # server.log

This is perfectly valid and still widely used.

Watch Out for Trailing Separators

This is where pathlib and os.path.basename can feel different:

python
1from pathlib import Path
2import os
3
4text = "/var/log/app/"
5
6print(Path(text).name)                 # app
7print(os.path.basename(text))          # ''
8print(os.path.basename(text.rstrip("/")))  # app

If your input path may end with a slash, Path(...).name is often more convenient.

Windows Paths on Any OS

If you need to parse Windows-style paths on a non-Windows machine, use PureWindowsPath so Python applies Windows rules explicitly.

python
1from pathlib import PureWindowsPath
2
3path = PureWindowsPath(r"C:\data\exports\daily.csv")
4print(path.name)   # daily.csv

This avoids cross-platform surprises when scripts process paths produced by another operating system. It is especially useful in ETL jobs, CI pipelines, and log-processing tools that receive path strings from mixed environments where the parsing rules should stay stable everywhere over time in production systems too consistently.

Filename Versus Directory Name

The “last part” might be a file name or a final directory name depending on the input.

python
1from pathlib import Path
2
3print(Path("/tmp/archive.zip").name)   # archive.zip
4print(Path("/tmp/folder/").name)       # folder

So the exact result depends on whether the path points to something that ends with a file-like component or a directory-like component.

A Small Utility Function

If your project handles mixed path styles, create one helper and keep the rules in one place.

python
1from pathlib import Path, PureWindowsPath
2
3def last_part(path_text: str) -> str:
4    if "\\" in path_text and (":" in path_text or path_text.startswith("\\\\")):
5        return PureWindowsPath(path_text).name
6    return Path(path_text).name
7
8print(last_part("/tmp/test.txt"))
9print(last_part(r"C:\tmp\test.txt"))

Centralizing this logic prevents repeated ad hoc string splitting across the codebase.

Why Manual Splitting Is Fragile

This is tempting:

python
path = "/var/log/app/server.log"
print(path.split("/")[-1])

But manual splitting breaks when:

  • the path uses backslashes
  • the input has trailing separators
  • the code runs on mixed path styles
  • UNC or drive-based Windows paths are involved

Path libraries already solve those cases more reliably.

Common Pitfalls

One common mistake is using split("/")[-1] everywhere and later discovering that Windows-style paths do not parse correctly.

Another issue is using os.path.basename on a path with a trailing slash and forgetting that it may return an empty string in that case.

A third pitfall is parsing Windows paths on Linux or macOS with Path instead of PureWindowsPath. The result may follow the current OS rules instead of the path string’s intended rules.

Summary

  • Use Path(path).name for the cleanest modern solution.
  • 'os.path.basename(path) is still valid and common in older code.'
  • Be careful with trailing separators, especially when using basename.
  • Use PureWindowsPath when parsing Windows paths on any OS.
  • Avoid manual string splitting for path extraction.

Course illustration
Course illustration

All Rights Reserved.