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


当前回答

上面的任何解决方案都有效,但在linux上,我发现扩展字符串末尾有一个换行符,这将阻止匹配成功。将strip()方法添加到末尾。例如:

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

其他回答

令人惊讶的是,这还没有被提及:

import os
fn = '/some/path/a.tar.gz'

basename = os.path.basename(fn)  # os independent
Out[] a.tar.gz

base = basename.split('.')[0]
Out[] a

ext = '.'.join(basename.split('.')[1:])   # <-- main part

# if you want a leading '.', and if no result `None`:
ext = '.' + ext if ext else None
Out[] .tar.gz

优点:

对我能想到的任何事情都能如愿以偿无模块无正则表达式跨平台易于扩展(例如,没有用于扩展的前导点,只有扩展的最后部分)

作为函数:

def get_extension(filename):
    basename = os.path.basename(filename)  # os independent
    ext = '.'.join(basename.split('.')[1:])
    return '.' + ext if ext else None

即使这个问题已经得到了回答,我也会在Regex中添加解决方案。

>>> import re
>>> file_suffix = ".*(\..*)"
>>> result = re.search(file_suffix, "somefile.ext")
>>> result.group(1)
'.ext'

使用splitext时,具有双扩展名的文件存在问题(例如file.tar.gz、file.tar.bz2等)

>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension 
'.gz'

但应该是:.tar.gz

可能的解决方案如下

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

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 os.path
extension = os.path.splitext(filename)[1][1:]

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