os.path.basename
basename(p) == split(p)[1] and dirname(p) == split(p)[0]. Unlike the Unix basename command, a trailing slash gives an empty basename: basename('/var/log/') is ''. dirname of a bare file name is '' — not '.'.
Demo
import posixpath (posixpath.dirname('/srv/app/main.py'), posixpath.basename('/srv/app/main.py'))
For '/var/log/' the last separator is the final character, so the basename is empty and dirname strips the trailing slash: '/var/log'. A bare name has no folder part: dirname is the empty string, which os functions do not accept as '.'. Climbing with dirname ends at '/' for an absolute path and at '' for a relative one.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| path | str | bytes | PathLike | yes | Any path. Nothing is checked on disk. |
Return value
str — basename: the text after the last separator. dirname: the text before it, without trailing separators (the root stays).
Common patterns
import os HERE = os.path.dirname(os.path.abspath(__file__))
import os stem = os.path.splitext(os.path.basename(path))[0]
import os name = os.path.basename(os.path.normpath(folder))
Examples
Pitfalls
import posixpath posixpath.basename('/var/log/')
import posixpath posixpath.basename(posixpath.normpath('/var/log/'))
import os try: os.listdir(os.path.dirname('data.csv')) except OSError as e: result = type(e).__name__ result
import os open('data.csv', 'w').close() os.listdir(os.path.dirname('data.csv') or '.')
import posixpath posixpath.dirname(r'C:\data\in.csv')
import ntpath ntpath.dirname(r'C:\data\in.csv')
When to use
- File name or folder of a str path
- Both at once → os.path.split
- pathlib code → p.name and p.parent
- The extension → splitext
Notes
FAQ
os.path.basename(path), or Path(path).name. Without the extension: os.path.splitext(os.path.basename(path))[0], or Path(path).stem.