在 Python 中从文件名中提取扩展名

新手上路,请多包涵

是否有从文件名中提取扩展名的功能?

原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 694
2 个回答

使用 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题