os.path.splitext Splits The Last Extension
os.path.splitext returns name and extension as a pair by splitting only the final dot, while basename and dirname carve up the path around it.
Code
import os
# 只拆最后一个点:tar.gz 的主体是 archive.tar,扩展名是 .gz
print(os.path.splitext("/tmp/archive.tar.gz"))
print(os.path.splitext("archive.backup.tar.gz"))
# 路径拆解:basename 取文件名,dirname 取目录
print(os.path.basename("/tmp/reports/daily.csv"), os.path.dirname("/tmp/reports/daily.csv"))
print(os.path.split("/tmp/reports/daily.csv"))
# 边界:无扩展名与点开头的隐藏文件都返回空扩展名
print(os.path.splitext("README"), os.path.splitext(".gitignore"))
# 多个点同样只拆最后一个
print(os.path.splitext("/tmp/reports/Q4.report.pdf"))Output
Captured from a sandboxed run of this snippet in the build pipeline.
('/tmp/archive.tar', '.gz')
('archive.backup.tar', '.gz')
daily.csv /tmp/reports
('/tmp/reports', 'daily.csv')
('README', '') ('.gitignore', '')
('/tmp/reports/Q4.report', '.pdf')How it works
os.path.splitext cuts a path exactly at its final dot: /tmp/archive.tar.gz splits into the root /tmp/archive.tar and the extension .gz, and archive.backup.tar.gz keeps archive.backup whole for the same reason — earlier dots are never touched. A name with no dot (README) or a dot-leading hidden file (.gitignore) yields an empty extension string instead of treating the leading dot as a separator. Around it, os.path.basename and os.path.dirname carve out the file name and the directory part, while os.path.split returns that same directory/name pair as one tuple, as the printed rows show.
Using it
Call splitext when you need the stem and extension separately — pairing it with basename covers the common “name without folder, extension without dot” breakdown. Because only the final dot splits, multi-dot names like Q4.report.pdf keep their inner suffixes in the stem, so detect formats by comparing the returned extension rather than counting dots.
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.