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


当前回答

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

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,即使只有一个扩展名也能正常工作

其他回答

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

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

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

例子:

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

将给您:“csv”

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

只需加入所有pathlib后缀。

>>> x = 'file/path/archive.tar.gz'
>>> y = 'file/path/text.txt'
>>> ''.join(pathlib.Path(x).suffixes)
'.tar.gz'
>>> ''.join(pathlib.Path(y).suffixes)
'.txt'

试试看:

files = ['file.jpeg','file.tar.gz','file.png','file.foo.bar','file.etc']
pen_ext = ['foo', 'tar', 'bar', 'etc']

for file in files: #1
    if (file.split(".")[-2] in pen_ext): #2
        ext =  file.split(".")[-2]+"."+file.split(".")[-1]#3
    else:
        ext = file.split(".")[-1] #4
    print (ext) #5

获取列表中的所有文件名拆分文件名并检查倒数第二个扩展名,它是否在penext列表中?如果是,则使用最后一个扩展名连接它,并将其设置为文件的扩展名如果没有,则只将最后一个扩展名作为文件的扩展名然后检查一下

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

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,即使只有一个扩展名也能正常工作