Extracting extension from filename in Python

2019-01-01 02:53发布

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

20条回答
回忆,回不去的记忆
2楼-- · 2019-01-01 03:29

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()
查看更多
春风洒进眼中
3楼-- · 2019-01-01 03:29

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])
查看更多
登录 后发表回答