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


当前回答

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

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

其他回答

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

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

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

最简单的获取方法是使用mimtypes,下面是示例:

import mimetypes

mt = mimetypes.guess_type("file name")
file_extension =  mt[0]
print(file_extension)

从Python中的文件名提取扩展名

Python os模块splitext()

splitext()函数将文件路径拆分为具有两个值的元组:root和extension。

import os
# unpacking the tuple
file_name, file_extension = os.path.splitext("/Users/Username/abc.txt")
print(file_name)
print(file_extension)

使用Pathlib模块获取文件扩展名

获取文件扩展名的Pathlib模块

import pathlib
pathlib.Path("/Users/pankaj/abc.txt").suffix
#output:'.txt'

使用os.path.splitext:

>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'

与大多数手动字符串拆分尝试不同,os.path.splitext将正确地将/a/b.c/d视为没有扩展名而不是扩展名.c/d,并将.bashrc视为没有延伸名而不是具有扩展名.bashrc:

>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')