Python截取路径中的文件名

来源:互联网 发布:在淘宝网买东西可靠吗 编辑:程序博客网 时间:2024/05/16 08:43

假设有一个文件的路径名为:“K:\Project\FilterDriver\DriverCodes\hello.txt”,而且路径和文件名都不是固定的。如何得到hello.txt这段字符串呢?

一、字符串分割–split()函数

?
1
2
path="K:/Project/FilterDriver/DriverCodes/hello.txt"
printpath.split("/")[-1]

执行结果:hello.txt。

二、使用basename()函数

?
1
2
3
import os.path
filePath="K:/Project/FilterDriver/DriverCodes/hello.txt"
printos.path.basename(filePath)

执行的结果仍然是hello.txt。