Last active
March 22, 2021 17:44
-
-
Save sethrh/0c4196080e092fe0015e0fe8c3166ba6 to your computer and use it in GitHub Desktop.
better_splitext.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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