第一种方法:splitext()方法
import os
def demo():
file_path = "E:\\测试.txt"
print(os.path.splitext(file_path)[-1])
demo()
执行上述代码,其输出结果为:
.txt
第二种方法:endswith()方法
def demo():
file_path = "E:\\测试.txt"
flag = file_path.endswith(".txt")
print(flag)
demo()
执行上述代码,其输出结果为:
True
第三种方法:判断后缀名是否在字符串中(若后缀为.txtd,这种会存在误判,不推荐)
def demo():
file_path = "E:\\测试.txt"
if ".txt" in file_path:
print(&