liveBook · Manning

Basename

As explained in The Quick Python Book, Fourth Edition

A basename is the final filename component of a pathname, excluding its preceding directory components.

A basename is the final file or directory name in a pathname, without the preceding directories. Python exposes it through os.path.basename and, with pathlib, the Path.name property. section 12.2.4 section 12.2.5

Use the basename alongside related pathname operations:

Reading the final component

import os from pathlib import Path path = os.path.join('some', 'directory', 'path.jpg') os.path.basename(path) # 'path.jpg' Path(path).name # 'path.jpg' Path(path).parent # some/directory Path(path).suffix # '.jpg' section 12.2.4 section 12.2.5

a_path = Path('some', 'directory', 'path.jpg')
a_path.name
 
'path.jpg'
 
print(a_path.parent)
 
some/directory
 
a_path.suffix
 
'.jpg'

Inspect a pathlib example showing the basename, parent directory, and filename suffix together. section 12.2.5

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the final component and demonstrates os.path and pathlib access, while deferring deeper filesystem validation.
Examples
Uses joined paths such as some/directory/path.jpg to show basename, parent directory, and extension results.
What you can do after
Apply it via os.path.basename or Path.name to retrieve a pathname's final component.
How it connects
Connects basename with pathname, dirname, split, splitext, pathlib, Path, parent, and suffix.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.