是否有从文件名中提取扩展名的功能?
ask by Alex translate from soYes.
(是。)
Useos.path.splitext
(see Python 2.X documentation or Python 3.X documentation ): (使用os.path.splitext
(请参阅Python 2.X文档或Python 3.X文档 ):)
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
Unlike most manual string-splitting attempts, os.path.splitext
will correctly treat /a/bc/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/bc/d
正确地视为不具有扩展名而不是扩展名.c/d
,并且将.bashrc
视为不具有扩展名而不是具有extension .bashrc
:)
>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')