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?
split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that. In the above example 'file. txt' component of path name is tail and '/home/User/Desktop/' is head.
path. splitext() method in Python is used to split the path name into a pair root and ext. Here, ext stands for extension and has the extension portion of the specified path while root is everything except ext part.
We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values - root and extension.
path. dirname() method in Python is used to get the directory name from the specified path.
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']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With