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


当前回答

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

其他回答

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

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

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太棒了!

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

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

此方法需要字典、列表或集合。您可以使用内置字符串方法使用“.endswitch”。这将在文件末尾的列表中搜索名称,只需使用str.endswith(fileName[index])即可完成。这更多用于获取和比较扩展名。

https://docs.python.org/3/library/stdtypes.html#string-方法

示例1:

dictonary = {0:".tar.gz", 1:".txt", 2:".exe", 3:".js", 4:".java", 5:".python", 6:".ruby",7:".c", 8:".bash", 9:".ps1", 10:".html", 11:".html5", 12:".css", 13:".json", 14:".abc"} 
for x in dictonary.values():
    str = "file" + x
    str.endswith(x, str.index("."), len(str))

示例2:

set1 = {".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"}
for x in set1:
   str = "file" + x
   str.endswith(x, str.index("."), len(str))

示例3:

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
for x in range(0, len(fileName)):
    str = "file" + fileName[x]
    str.endswith(fileName[x], str.index("."), len(str))

示例4

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
str = "file.txt"
str.endswith(fileName[1], str.index("."), len(str))

具有输出的示例5、6、7

示例8

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
exts = []
str = "file.txt"
for x in range(0, len(x)):
    if str.endswith(fileName[1]) == 1:
         exts += [x]