代码之家  ›  专栏  ›  技术社区  ›  ravishankar chavare

在完整文件路径中搜索用户关键字,并根据搜索结果给出输出目录或文件名。

  •  -1
  • ravishankar chavare  · 技术社区  · 6 年前

    我有完整的文件路径和用户搜索关键字,如果用户输入在basefilename打印完整的文件名。

    如果搜索的关键字是文件夹部分,则打印路径直到搜索到的路径

    例子: filepath='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")
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   DSLima90    6 年前

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

    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'
    
        2
  •  0
  •   Dude    6 年前

    如果我理解你的问题正确,下面的代码就是你需要的。

    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))