假设有一个文件的路径名为:“K:\Project\FilterDriver\DriverCodes\hello.txt”,而且路径和文件名都不是固定的。如何得到hello.txt这段字符串呢?
一、字符串分割–split()函数
|
1
2
|
path="K:/Project/FilterDriver/DriverCodes/hello.txt"
print path.split("/")[-1]
|
执行结果:hello.txt。
二、使用basename()函数
|
1
2
3
|
import os.path
filePath = "K:/Project/FilterDriver/DriverCodes/hello.txt"
print os.path.basename(filePath)
|
执行的结果仍然是hello.txt。
本文介绍两种从完整路径中提取文件名的方法:一是使用Python内置的split()函数;二是利用os.path模块中的basename()函数。

3万+

被折叠的 条评论
为什么被折叠?



