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


当前回答

import os.path
extension = os.path.splitext(filename)[1][1:]

只获取扩展名的文本,而不获取点。

其他回答

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

import mimetypes

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

使用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', '')

虽然这是一个古老的话题,但我想知道为什么在本例中没有提到一个非常简单的python api rpartition:

要获取给定文件绝对路径的扩展名,只需键入:

filepath.rpartition('.')[-1]

例子:

path = '/home/jersey/remote/data/test.csv'
print path.rpartition('.')[-1]

将给您:“csv”

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

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

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