liveBook · Manning

Os.path.basename

As explained in The Quick Python Book, Fourth Edition

os.path.basename is a Python function that returns the final component of a filesystem pathname.

os.path.basename returns the final component of a filesystem pathname—the file or directory name at the end. section 12.2.4

Extract a filename

import os os.path.basename(os.path.join('some', 'directory', 'path.jpg')) # 'path.jpg' section 12.2.4

Related pathname operations separate complementary parts:

  • os.path.split returns the directory portion and basename as a two-element tuple. section 12.2.4
  • os.path.dirname returns the path before the final component. section 12.2.4
  • os.path.splitext separates a dotted extension from the rest of the pathname. section 12.2.4
import os
os.path.basename(os.path.join('some', 'directory', 'path.jpg'))
 
'path.jpg'
 
os.path.dirname(os.path.join('some', 'directory', 'path.jpg'))
 
'some/directory'

Compare basename extraction with dirname using the same constructed pathname. section 12.2.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the return value and demonstrates one runnable example, but does not explain implementation internals or extensive edge cases.
Examples
Uses os.path.join to construct some/directory/path.jpg, then extracts path.jpg.
What you can do after
Apply it via Python's os.path API to retrieve the final component of a constructed pathname.
How it connects
Connects basename with os.path.join, os.path.split, os.path.dirname, and os.path.splitext.

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.