我正在使用python os.path.splitext()并且很好奇是否可以将文件名与多个"."的扩展名分开?例如,使用splitext的"foobar.aux.xml".文件名不同于[foobar,foobar.xml,foobar.aux.xml].有没有更好的办法?
Art*_*par 25
分裂os.extsep.
>>> import os
>>> 'filename.ext1.ext2'.split(os.extsep)
['filename', 'ext1', 'ext2']
Run Code Online (Sandbox Code Playgroud)
如果你想要第一个点之后的所有内容:
>>> 'filename.ext1.ext2'.split(os.extsep, 1)
['filename', 'ext1.ext2']
Run Code Online (Sandbox Code Playgroud)
如果您使用的路径包含可能包含点的目录:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
你可以尝试:
names = pathname.split('.')
filename = names[0]
extensions = names[1:]
Run Code Online (Sandbox Code Playgroud)
如果你想使用splitext,你可以使用类似的东西:
import os
path = 'filename.es.txt'
while True:
path, ext = os.path.splitext(path)
if not ext:
print path
break
else:
print ext
Run Code Online (Sandbox Code Playgroud)
生产:
.txt
.es
filename
Run Code Online (Sandbox Code Playgroud)