是否有从文件名中提取扩展名的功能?


当前回答

对于简单的用例,一个选项可能是从点拆分:

>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'

文件没有扩展名时没有错误:

>>> "filename".split(".")[-1]
'filename'

但你必须小心:

>>> "png".split(".")[-1]
'png'    # But file doesn't have an extension

也不会在Unix系统中处理隐藏文件:

>>> ".bashrc".split(".")[-1]
'bashrc'    # But this is not an extension

对于一般用途,首选os.path.splitext

其他回答

即使这个问题已经得到了回答,我也会在Regex中添加解决方案。

>>> import re
>>> file_suffix = ".*(\..*)"
>>> result = re.search(file_suffix, "somefile.ext")
>>> result.group(1)
'.ext'

您可以使用以下代码拆分文件名和扩展名。

    import os.path
    filenamewithext = os.path.basename(filepath)
    filename, ext = os.path.splitext(filenamewithext)
    #print file name
    print(filename)
    #print file extension
    print(ext)
def NewFileName(fichier):
    cpt = 0
    fic , *ext =  fichier.split('.')
    ext = '.'.join(ext)
    while os.path.isfile(fichier):
        cpt += 1
        fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
    return fichier

为了好玩。。。只需收集dict中的扩展,并在文件夹中跟踪所有扩展。然后,只要拉动你想要的延伸部分。

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)
# 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:

    @staticmethod
    def 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) + ext
            else:
                return ""