Extracting extension from filename in Python
有没有从文件名中提取扩展名的函数?
Yes. Use os.path.splitext
:
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
import os.path
extension = os.path.splitext(filename)[1]
New in version 3.4.
import pathlib
print(pathlib.Path('yourPathGoesHere').suffix)
I'm surprised no one has mentioned pathlib
yet, pathlib
IS awesome!
If you need all the suffixes (eg if you have a .tar.gz
), .suffixes
will return a list of them!
上一篇: Linux管道(转换
下一篇: 在Python中从文件名中提取扩展名