python - 在完整文件路径中搜索用户关键字并根据搜索结果给出输出目录或文件名
问题描述
我有完整的文件路径,如果用户输入在 basefilename 中,则用户搜索关键字打印完整文件名。
如果搜索的关键字是文件夹部分,则打印路径,直到搜索到的路径
示例:文件路径='D:\ABDCD\Desktop\old.net\BestchPring\Vs.net\CommanUsegftrol.ascx.cs'
如果用户搜索桌面:输出应为 D:\ABDCD\Desktop
如果用户搜索命令:输出应该是:D:\ABDCD\Desktop\old.net\BestchPring\Vs.net\CommanUsegftrol.ascx.cs
import os
searchtext='cs'
filepath='D:\ABDCD\Desktop\old.net\BestchPring\Vs.net\CommanUsegftrol.ascx.cs'
fle=filepath.lower()
searcheddata=fle.find(searchtext.lower())
if searchtext in os.path.basename(filepath):
print("File: ",filepath)
elif(searcheddata!=-1):
lastdir=fle[searcheddata:].find('\\')
print("Folder: ",filepath[:searcheddata+lastdir])
else:
print("File And Folder Both Not Found")
解决方案
我不知道我是否理解,但我认为这就是你想要的:
filepath='D:\ABDCD\Desktop\old.net\BestchPring\Vs.net\CommanUsegftrol.ascx.cs'
def findpath(searchtext):
path = os.path.normpath(filepath)
while path != "":
path, folder = os.path.split(path)
if searchtext.lower() in folder.lower():
return os.path.join(path, folder)
return "Not found"
结果:
In [1]: findpath("des")
Out[1]: 'D:\ABDCD\Desktop'
In [2]: findpath("comman")
Out[2]: 'D:\ABDCD\Desktop\old.net\BestchPring\Vs.net\CommanUsegftrol.ascx.cs'
推荐阅读
- java - 如何根据谓词过滤 Iterable?
- .htaccess - 两次通过同一个 htaccess 文件
- php - Laravel - 刀片检查对象是否有关系
- excel - Excel VBA Dir() 文件类型更改时出错
- rest - 安装 nuget 包 Swashbuckle 时出错
- angular - 如何从服务器端向客户端注入价值?
- c# - 向数据库添加新的子实体也会插入一个新的空父实体
- python-3.x - git commit 错误:python 2 和 python 3.7 之间的版本不一致
- python - 检查二维矩阵中的每个元素
- mysql - MySQL 5.7 - ASCII 字符串中的每个字符