Extracting extension from filename in Python

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

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

24条回答
  •  长发绾君心
    2020-11-22 14:16

    Another solution with right split:

    # 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])
    

提交回复
热议问题