Separating file extensions using python os.path module

From the help of the function:

Extension is everything from the last dot to the end, ignoring leading dots.

So the answer is no, you can't do it with this function.


you could try with:

names = pathname.split('.')
filename = names[0]
extensions = names[1:]

if you want to use splitext, you can use something like:

import os

path = 'filename.es.txt'

while True:
    path, ext = os.path.splitext(path)
    if not ext:
        print path
        break
    else:
        print ext

produces:

.txt
.es
filename

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']

Tags:

Python