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

2024-09-27 04:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

示例: filepath='D:\abdd\桌面\旧.net\贝斯特普林\与.net\通信控制.ascx.cs'

如果用户搜索台: 输出应为D:\abdd\Desktop

如果用户搜索命令: 输出应为:D:\abdd\Desktop\旧.net\贝斯特普林\与.net\通信控制.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")

Tags: 用户路径netos关键字cslowerprint
2条回答

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

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

我不知道我是否明白,但我想这就是你想要的:

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'

相关问题 更多 >

    热门问题