Issue
I’m working in python with os.path.splitext()
and curious if it is possible to separate filenames from extensions with multiple “.”? e.g. “foobar.aux.xml” using splitext. Filenames vary from [foobar, foobar.xml, foobar.aux.xml]. Is there a better way?
Solution
Split with os.extsep
.
>>> import os
>>> 'filename.ext1.ext2'.split(os.extsep)
['filename', 'ext1', 'ext2']
If you want everything after the first dot:
>>> 'filename.ext1.ext2'.split(os.extsep, 1)
['filename', 'ext1.ext2']
If you are using paths with directories that may contain dots:
>>> def my_splitext(path):
... """splitext for paths with directories that may contain dots."""
... li = []
... path_without_extensions = os.path.join(os.path.dirname(path), os.path.basename(path).split(os.extsep)[0])
... extensions = os.path.basename(path).split(os.extsep)[1:]
... li.append(path_without_extensions)
... # li.append(extensions) if you want extensions in another list inside the list that is returned.
... li.extend(extensions)
... return li
...
>>> my_splitext('/path.with/dots./filename.ext1.ext2')
['/path.with/dots./filename', 'ext1', 'ext2']
Answered By – Artur Gaspar
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0