我有完整的文件路径,如果用户输入的基本文件名显示完整的文件名,则用户搜索关键字。
如果搜索到的关键字是文件夹的一部分,则打印路径,直到搜索到该路径为止
示例: filepath ='D:\ ABDCD \ Desktop \ old.net \ BestchPring \ Vs.net \ CommanUsegftrol.ascx.cs'
如果用户搜索台: 输出应为D:\ ABDCD \ Desktop
如果用户搜索Comman: 输出应为: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")
答案 0 :(得分:1)
我不知道我是否理解,但是我想这就是你想要的:
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'
答案 1 :(得分:0)
如果我正确理解了您的问题,那么下面的代码就是您所需要的。
def filter_by_keyword(directory, pattern):
root = ...
if os.path.dirname(directory):
for path, subdir, files in os.walk(root):
for fn in fnmatch.filter(files, pattern):
print('Matched variant found in "{}", fn: "{}"'.format(path, fn))