# to get extension only
s = 'test.ext'
if '.' in s: ext = s.rsplit('.', 1)[1]
# or, to get file name and extension
def split_filepath(s):"""get filename and extension from filepathfilepath -> (filename, extension)"""if not '.' in s: return (s, '')r = s.rsplit('.', 1)return (r[0], r[1])
# try this, it works for anything, any length of extension# e.g www.google.com/downloads/file1.gz.rs -> .gz.rs
import os.path
class LinkChecker:
@staticmethoddef get_link_extension(link: str)->str:if link is None or link == "":return ""else:paths = os.path.splitext(link)ext = paths[1]new_link = paths[0]if ext != "":return LinkChecker.get_link_extension(new_link) + extelse:return ""
import osfn = '/some/path/a.tar.gz'
basename = os.path.basename(fn) # os independentOut[] a.tar.gz
base = basename.split('.')[0]Out[] a
ext = '.'.join(basename.split('.')[1:]) # <-- main part
# if you want a leading '.', and if no result `None`:ext = '.' + ext if ext else NoneOut[] .tar.gz
好处:
我能想到的任何东西都能正常工作
没有模块
没有正则表达式
跨平台
易于扩展(例如,扩展没有前导点,只有扩展的最后一部分)
作为函数:
def get_extension(filename):basename = os.path.basename(filename) # os independentext = '.'.join(basename.split('.')[1:])return '.' + ext if ext else None
>>> x = 'file/path/archive.tar.gz'>>> y = 'file/path/text.txt'>>> ''.join(pathlib.Path(x).suffixes)'.tar.gz'>>> ''.join(pathlib.Path(y).suffixes)'.txt'
import os
search = {}
for f in os.listdir(os.getcwd()):fn, fe = os.path.splitext(f)try:search[fe].append(f)except:search[fe]=[f,]
extensions = ('.png','.jpg')for ex in extensions:found = search.get(ex,'')if found:print(found)