Extracting extension from filename in Python

后端 未结 24 2409
感情败类
感情败类 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

提交回复
热议问题