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


当前回答

这是一种直接的字符串表示技术:我看到提到了很多解决方案,但我认为大多数都在考虑拆分。然而,每次出现“.”时,Split都会执行此操作。您更希望查找的是分区。

string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-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:

    @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 ""

3.4版新增。

import pathlib

print(pathlib.Path('yourPath.example').suffix) # '.example'
print(pathlib.Path("hello/foo.bar.tar.gz").suffixes) # ['.bar', '.tar', '.gz']

我很惊讶还没有人提到pathlib,pathlib太棒了!

只需加入所有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'

值得在那里加一个较低的,这样你就不会发现自己为什么JPG没有出现在你的列表中。

os.path.splitext(filename)[1][1:].strip().lower()

另一种右拆分解决方案:

# 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 filepath 
    filepath -> (filename, extension)
    """
    if not '.' in s: return (s, '')
    r = s.rsplit('.', 1)
    return (r[0], r[1])