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:
- Split a pathname into its directory portion and final name with os.path.split. section 12.2.4
- Retrieve the preceding directory with os.path.dirname or the pathlib parent property. section 12.2.4 section 12.2.5
- Separate a filename from its dotted extension with os.path.splitext or Path.suffix. section 12.2.4 section 12.2.5
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
