os.path.splitext
splitext cuts at the last dot of the last path component: 'archive.tar.gz' gives '.gz', a dot in a folder name is ignored, and a name made only of a leading dot (.bashrc) has no extension. The extension keeps its dot and its case.
Demo
import posixpath posixpath.splitext('reports/2026/summary.pdf')
The extension is everything from the last dot of the file name: backup.tar.gz gives '.gz', so replacing it gives site.tar.zip, not site.zip. The leading dot of .bashrc does not count, and the dot in conf.d is in a folder, not in the file name — both give an empty extension. With no extension the new one is simply appended.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| path | str | bytes | PathLike | yes | A file name or full path; only its last component is examined. |
Return value
tuple[str, str] — (root, ext): ext is '' or starts with '.', and root + ext == path.
Common patterns
import os IMAGES = {'.png', '.jpg', '.jpeg', '.gif'} images = [n for n in os.listdir(folder) if os.path.splitext(n)[1].lower() in IMAGES]
import os out_path = os.path.splitext(in_path)[0] + '.json'
import os def suffixes(name): exts = [] while True: name, ext = os.path.splitext(name) if not ext: return exts exts.insert(0, ext)
Examples
Pitfalls
[p.split('.')[-1] for p in ['/etc/conf.d/nginx', 'Makefile']]
import posixpath [posixpath.splitext(p)[1] for p in ['/etc/conf.d/nginx', 'Makefile']]
import posixpath posixpath.splitext('backup.tar.gz')[0]
import posixpath name = posixpath.basename('backup.tar.gz') name.split('.', 1)[0]
When to use
- Checking or changing a file extension of a str path
- pathlib code → p.suffix, p.suffixes, p.stem, p.with_suffix('.json')
- Detecting the real file type → mimetypes.guess_type (by name) or reading the file header
Notes
FAQ
os.path.splitext(path)[1] — it includes the dot ('.pdf'), or is '' when there is none. With pathlib: Path(path).suffix.