Extracting extension from filename in Python

后端 未结 24 2567
感情败类
感情败类 2020-11-22 13:23

Is there a function to extract the extension from a filename?

24条回答
  •  广开言路
    2020-11-22 14:16

    try this:

    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
    
    1. get all file name inside the list
    2. splitting file name and check the penultimate extension, is it in the pen_ext list or not?
    3. if yes then join it with the last extension and set it as the file's extension
    4. if not then just put the last extension as the file's extension
    5. and then check it out

提交回复
热议问题