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


当前回答

您可以对文件名使用拆分:

f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

这不需要额外的库

其他回答

name_only=file_name[:filename.index(".")

这将为您提供文件名,最多为第一个“.”,这将是最常见的。

只需加入所有pathlib后缀。

>>> x = 'file/path/archive.tar.gz'
>>> y = 'file/path/text.txt'
>>> ''.join(pathlib.Path(x).suffixes)
'.tar.gz'
>>> ''.join(pathlib.Path(y).suffixes)
'.txt'
# 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 ""
a = ".bashrc"
b = "text.txt"
extension_a = a.split(".")
extension_b = b.split(".")
print(extension_a[-1])  # bashrc
print(extension_b[-1])  # txt

为了好玩。。。只需收集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)