首页 > 解决方案 > 在完整文件路径中搜索用户关键字并根据搜索结果给出输出目录或文件名

问题描述

我有完整的文件路径,如果用户输入在 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")

标签: python

解决方案


我不知道我是否理解,但我认为这就是你想要的:

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'

推荐阅读