all Python 3osfunction
os.path.splitext()
os.path
Splits a path into the pair (root, ext), where ext is the file extension including the dot. Handy for changing an extension.
Syntax
os.path.splitext(path) -> (root, ext)
It cuts only the last extension: splitext('a.tar.gz') gives ('a.tar', '.gz'), not ('a', '.tar.gz'). A leading dot is not an extension: splitext('.bashrc') returns ('.bashrc', ''). A dot in a directory name is ignored as well: splitext('dir.d/file') has no extension. When comparing extensions normalise case: on Windows '.TXT' and '.txt' are the same type.
Examples
import os
print(os.path.splitext('report.pdf')) # → ('report', '.pdf')
print(os.path.splitext('archive.tar.gz')) # → ('archive.tar', '.gz')
print(os.path.splitext('no_extension')) # → ('no_extension', '')
name, ext = os.path.splitext('data.csv')
print(name + '.xlsx') # → data.xlsx
print(os.path.splitext('/home/user/file.py')) # → ('/home/user/file', '.py')
See also
Open in the full glossarydocs.python.orgReport an inaccuracy