Skip to content

Instantly share code, notes, and snippets.

@sethrh
Last active March 22, 2021 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sethrh/0c4196080e092fe0015e0fe8c3166ba6 to your computer and use it in GitHub Desktop.
Save sethrh/0c4196080e092fe0015e0fe8c3166ba6 to your computer and use it in GitHub Desktop.
better_splitext.py
# SRH 17-Mar-2021
"""
Improved os.path.splitext which properly deals with files containing multiple
dots in extensions.
"""
import os
def better_splitext(name):
"""Like os.path.splitext, but aware of extensions with multiple dots.
>>> f = 'spam.jpeg'
>>> better_splitext(f)
('spam', '.jpeg')
>>> f = 'eggs.tar.gz'
>>> better_splitext(f)
('eggs', '.tar.gz')
>>> f = '/home/kurtk/.local/directory_with_dots/foobar.tar.bz2'
>>> better_splitext(f)
('/home/kurtk/.local/directory_with_dots/foobar', '.tar.bz2')
>>> f = 'file..ext'
>>> better_splitext(f)
('file', '..ext')
>>> f = ''
>>> better_splitext(f)
('', '')
>>> f = '........'
>>> better_splitext(f)
('........', '')
>>> f = '.png'
>>> better_splitext(f)
('.png', '')
"""
exts = []
while True:
base, ext = os.path.splitext(name)
if ext == '':
# no more extensions found
break
exts.insert(0, ext)
name = base
return base, ''.join(exts)
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment