Explain Codes LogoExplain Codes Logo

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

python
pathlib
os.path
file-management
Nikita BarsukovbyNikita Barsukov·Feb 18, 2025
TLDR

Get the terminal segment of a filepath with os.path.basename() or Path.name:

import os from pathlib import Path # os.path approach print(os.path.basename('/foo/bar/item.ext')) # 'item.ext' # pathlib method print(Path('/foo/bar/item.ext').name) # 'item.ext'

These methods give you a no-hassle solution to reach the ending part of any path, irrespective of files or directories.

Managing unexpected cases

Path usage can throw up particular situations such as trailing slashes or empty paths. Below is how to negotiate these hurdles:

Using os.path to sidestep common issues

# Though trailing slash path feels like 'endgame', we're just getting started. trail_slash_path = "/foo/bar/" norm_trail_slash_path = os.path.normpath(trail_slash_path) print(os.path.basename(norm_trail_slash_path)) # 'bar' # Empty path: does emptiness have a name? Let's find out. empty_path = "" print(os.path.basename(empty_path)) # ''

Using pathlib for a seamless approach

# Pathlib is like a 'no worries' approach, handling trailing & empty paths like a pro. trail_slash_path = Path("/foo/bar/") print(trail_slash_path.name) # 'bar' empty_path = Path("") print(empty_path.name) # ''

We see that os.path requires some pre-cleanup with os.path.normpath for optimal results, pathlib provides neatly groomed solutions right from the outset.

File vs Folder: The Directory Dilemma

When needed to discern between files and directories or fetch the name of the last directory, you can fine-tune your method thus:

Identifying if a path leads to a directory:

# Like asking, "Are you a folder?" The path responds. if os.path.isdir('/foo/bar/'): print("Yes, this is a directory.") if Path('/foo/bar/').is_dir(): print("Indeed, this is a directory.")

This simple interrogation can guide informed decisions for further path processing.

Extracting the last directory name:

Paths ending with directories can stump os.path.basename or Path.name as:

# os.path sounds puzzlingly silent at this: print(os.path.basename('/foo/bar/')) # '' # pathlib to the rescue: print(Path('/foo/bar/').parent.name) # 'bar'

The parent.name property of pathlib.Path objects cunningly bypasses the stumbling block, fetching the directory name even in the face of a trailing slash.

Delving deeper with pathlib

Complex path manipulations, beyond just the tail end, can be expertly managed with the object-oriented pathlib:

Extracting varied path elements

p = Path('/foo/bar/item.ext') print(p.stem) # 'item' print(p.suffix) # '.ext' print(p.parent) # '/foo/bar'

Across Operating Systems, pathlib stands firm

pathlib scores by being OS-agnostic, thus making your code way more portable:

# Windows path treating it no different than POSIX paths, like an unbiased ref! windows_path = Path(r"C:\Users\Name\file.txt") print(windows_path.name) # 'file.txt'

Easy path operations

Pathlib paths make path combination, listing, and examination a breeze:

# Combining paths like a happy family reunion. new_path = posix_path.parent / 'newfile.txt' print(new_path) # '/home/name/newfile.txt' # Listing directory contents, peeking into each room. for child in posix_path.parent.iterdir(): print(child) # Announces each child in the directory