在Python中从文件名提取扩展名 [英] Extracting extension from filename in Python
本文介绍了在Python中从文件名提取扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有从文件名中提取扩展名的功能?
Is there a function to extract the extension from a filename?
推荐答案
是.使用os.path.splitext
(请参阅 Python 2.X文档或 Python 3.X文档) :
Yes. Use os.path.splitext
(see Python 2.X documentation or Python 3.X documentation):
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
与大多数手动字符串拆分尝试不同,os.path.splitext
将正确地将/a/b.c/d
视为没有扩展名而不是扩展名.c/d
,并且将.bashrc
视为没有扩展名而不是扩展名.bashrc
:
Unlike most manual string-splitting attempts, os.path.splitext
will correctly treat /a/b.c/d
as having no extension instead of having extension .c/d
, and it will treat .bashrc
as having no extension instead of having extension .bashrc
:
>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')
这篇关于在Python中从文件名提取扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文