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:05
filename='ext.tar.gz'
extension = filename[filename.rfind('.'):]
查看更多
十年一品温如言
3楼-- · 2019-01-01 03:05

This is a direct string representation techniques : I see a lot of solutions mentioned, but I think most are looking at split. Split however does it at every occurrence of "." . What you would rather be looking for is partition.

string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]
查看更多
呛了眼睛熬了心
4楼-- · 2019-01-01 03:07
import os.path
extension = os.path.splitext(filename)[1]
查看更多
姐姐魅力值爆表
5楼-- · 2019-01-01 03:07
import os.path
extension = os.path.splitext(filename)[1][1:]

To get only the text of the extension, without the dot.

查看更多
无色无味的生活
6楼-- · 2019-01-01 03:12

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() 
查看更多
冷夜・残月
7楼-- · 2019-01-01 03:13

You can use a split on a filename:

f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

This does not require additional library

查看更多
登录 后发表回答