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


当前回答

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

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

其他回答

a = ".bashrc"
b = "text.txt"
extension_a = a.split(".")
extension_b = b.split(".")
print(extension_a[-1])  # bashrc
print(extension_b[-1])  # txt

我知道我迟到了

这是我的简单解决方案

file = '/foo/bar/whatever.ext'
extension = file.split('.')[-1]
print(extension)

#output will be ext

如果您想提取最后一个文件扩展名,如果它有多个

class functions:
    def listdir(self, filepath):
        return os.listdir(filepath)
    
func = functions()

os.chdir("C:\\Users\Asus-pc\Downloads") #absolute path, change this to your directory
current_dir = os.getcwd()

for i in range(len(func.listdir(current_dir))): #i is set to numbers of files and directories on path directory
    if os.path.isfile((func.listdir(current_dir))[i]): #check if it is a file
        fileName = func.listdir(current_dir)[i] #put the current filename into a variable
        rev_fileName = fileName[::-1] #reverse the filename
        currentFileExtension = rev_fileName[:rev_fileName.index('.')][::-1] #extract from beginning until before .
        print(currentFileExtension) #output can be mp3,pdf,ini,exe, depends on the file on your absolute directory

输出为mp3,即使只有一个扩展名也能正常工作

如果你喜欢正则表达式,那就是一个真正的单行。即使中间有额外的“.”也无关紧要

import re

file_ext = re.search(r"\.([^.]+)$", filename).group(1)

查看此处查看结果:单击此处

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

    import os.path
    filenamewithext = os.path.basename(filepath)
    filename, ext = os.path.splitext(filenamewithext)
    #print file name
    print(filename)
    #print file extension
    print(ext)