使用 os.path.splitext : >>> 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/b.c/d as having no extension instead of having extension .c/d , and it will .bashrc 因为没有扩展名而不是扩展名 .bashrc : >>> os.path.splitext('/a/b.c/d') ('/a/b.c/d', '') >>> os.path.splitext('.bashrc') ('.bashrc', '') 原文由 nosklo 发布,翻译遵循 CC BY-SA 4.0 许可协议
3.4 版中的新功能。 import pathlib print(pathlib.Path('yourPath.example').suffix) # '.example' print(pathlib.Path("hello/foo.bar.tar.gz").suffixes) # ['.bar', '.tar', '.gz'] 我很惊讶没有人提到 pathlib 但是, pathlib 太棒了! 原文由 jeromej 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
os.path.splitext
: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.bashrc
因为没有扩展名而不是扩展名.bashrc
: