您的当前位置:首页正文

python 如何获取文件名后缀

来源:花图问答

方法:

使用 os.path.splitext(file)[0] 可获得文件名 。

使用 os.path.splitext(file)[-1] 可获得以 . 开头的文件后缀名 。

import os
file = "Hello.py"

获取前缀(文件名称)

assert os.path.splitext(file)[0] == "Hello"

获取后缀(文件类型)

assert os.path.splitext(file)[-1] == ".py"
assert os.path.splitext(file)[-1][1:] == "py"

python学习网,免费的在线学习,欢迎关注!