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


当前回答

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

其他回答

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

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

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

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”

这是在一行中同时获取文件名和扩展名的最简单方法。

fName, ext = 'C:/folder name/Flower.jpeg'.split('/')[-1].split('.')

>>> print(fName)
Flower
>>> print(ext)
jpeg

与其他解决方案不同,您不需要为此导入任何包。

另一种右拆分解决方案:

# to get extension only

s = 'test.ext'

if '.' in s: ext = s.rsplit('.', 1)[1]

# or, to get file name and extension

def split_filepath(s):
    """
    get filename and extension from filepath 
    filepath -> (filename, extension)
    """
    if not '.' in s: return (s, '')
    r = s.rsplit('.', 1)
    return (r[0], r[1])