Python: Split the final extension while preserving dotfiles
os.path.splitext() separates a filename into a root and its final extension. Leading dots in the final path component belong to the root, which makes a name such as .env different from a name ending in .env.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as filename_extension.py in an empty working directory:
from os.path import splitext
for name in (".env", "report.tar.gz", ".env.local", "archive."):
root, extension = splitext(name)
assert root + extension == name
print(f"{name!r}: root={root!r}, extension={extension!r}")Run it without -O so any assertions remain enabled:
python3 filename_extension.pyCaptured output:
'.env': root='.env', extension=''
'report.tar.gz': root='report.tar', extension='.gz'
'.env.local': root='.env', extension='.local'
'archive.': root='archive', extension='.'.env has no extension. The final suffix of report.tar.gz is .gz, leaving report.tar as the root. A trailing dot is itself an extension, and .env.local splits at its last dot. Each pair reconstructs the input exactly.
Limits and cleanup
This is lexical parsing using the platform’s path rules; the example was run on Linux. It does not inspect file contents or validate a file type. If your application treats .tar.gz as one compound extension, give that convention its own explicit handling.
After testing, remove the example script from its working directory:
rm -- filename_extension.pyReference
Acknowledgements
This post was created with assistance from AI.