Extracting extension from filename in Python

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

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

相关标签:
24条回答
  • 2020-11-22 13:57

    For simple use cases one option may be splitting from dot:

    >>> filename = "example.jpeg"
    >>> filename.split(".")[-1]
    'jpeg'
    

    No error when file doesn't have an extension:

    >>> "filename".split(".")[-1]
    'filename'
    

    But you must be careful:

    >>> "png".split(".")[-1]
    'png'    # But file doesn't have an extension
    

    Also will not work with hidden files in Unix systems:

    >>> ".bashrc".split(".")[-1]
    'bashrc'    # But this is not an extension
    

    For general use, prefer os.path.splitext

    0 讨论(0)
  • 2020-11-22 13:58

    For funsies... just collect the extensions in a dict, and track all of them in a folder. Then just pull the extensions you want.

    import os
    
    search = {}
    
    for f in os.listdir(os.getcwd()):
        fn, fe = os.path.splitext(f)
        try:
            search[fe].append(f)
        except:
            search[fe]=[f,]
    
    extensions = ('.png','.jpg')
    for ex in extensions:
        found = search.get(ex,'')
        if found:
            print(found)
    
    0 讨论(0)
  • 2020-11-22 13:59

    With splitext there are problems with files with double extension (e.g. file.tar.gz, file.tar.bz2, etc..)

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

    but should be: .tar.gz

    The possible solutions are here

    0 讨论(0)
  • 2020-11-22 14:01

    Any of the solutions above work, but on linux I have found that there is a newline at the end of the extension string which will prevent matches from succeeding. Add the strip() method to the end. For example:

    import os.path
    extension = os.path.splitext(filename)[1][1:].strip() 
    
    0 讨论(0)
  • 2020-11-22 14:04

    worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.

    os.path.splitext(filename)[1][1:].strip().lower()
    
    0 讨论(0)
  • 2020-11-22 14:06
    filename='ext.tar.gz'
    extension = filename[filename.rfind('.'):]
    
    0 讨论(0)
提交回复
热议问题