【问题标题】:Stop the search at the first match, in a folder of +900 folders PYTHON在第一次匹配时停止搜索,在 +900 个文件夹 PYTHON 的文件夹中
【发布时间】:2020-07-04 19:44:40
【问题描述】:

我有一个文件夹(C:\Users\jrange14\Desktop\Jobs),里面有900多个文件夹,格式如下:

“三个数字”+“_”+“工作名称”

示例:888_jtjdt

我想做一个搜索,用户只需要求输入一个名为 JOB 的三位数,程序将搜索整个文件夹并找到所需的文件夹,只有文件夹的前 3 个字符。

这是获取该文件夹路径的 Python 代码:

import os
import fnmatch

#Job to find
job = "888"

#This is the folder where all the "jobs" are
eng_path=r"C:\Users\jrange14\Desktop\Jobs"

#Define the path in which we will work
os.chdir(eng_path)
path = os.getcwd()
print(path)

#Look in the directory
for dirs in os.listdir():

    if fnmatch.fnmatch(dirs, job+"*"):
        #print(dirs)
        job_name = dirs

job_path=eng_path+'\\'+job_name

print(job_path)

使用这段代码,我可以得到 3 件事, 工作目录:

C:\Users\jrange14\Desktop\Jobs

所需文件夹的全名:

888_jtjdt

和前两个相加得到那个文件夹的完整路径:

C:\Users\jrange14\Desktop\Jobs\888_jtjdt

问题是这段代码需要很长时间才能获得这个答案,因为文件夹内有很多文件夹(超过 900 个)并且每个文件夹都与输入相匹配。

据我所知,我的问题在这里:

#Look in the directory
for dirs in os.listdir():

    if fnmatch.fnmatch(dirs, job+"*"):
        #print(dirs)
        job_name = dirs

有了这个for,我看到它遍历了整个目录,寻找我们输入的匹配。即使程序找到了所需的文件夹,它也会继续在整个目录中寻找另一个

由于每个职位的前三个数字互不相同,因此无需继续寻找其他可能的匹配项。

如何在第一场比赛中停止程序?

【问题讨论】:

  • 要退出循环,有break 语句。另请查看glob 模块,它可能有助于加快整个过程。
  • 我尝试了glob 模块,但似乎它的工作方式相同

标签: python directory path match listdir


【解决方案1】:

使程序更快的解决方案是使用generator。无论何时找到实际文件,使用os.listdir() 将花费几乎相同的时间,因为它不是生成器,它不会在每次迭代期间生成每个结果,它会列出 all文件首先进入内存,然后遍历它们。

使用path.py:

from path import Path

eng_path = r"C:\Users\jrange14\Desktop\Jobs"
d = Path(eng_path)
job = "888"

for dirs in d.dirs(f'{job}_*'):
    print(dirs)
    break

【讨论】:

    【解决方案2】:

    你能试一试吗?

    import os
    
    #Job to find
    job_number = "888_"
    
    #This is the folder where all the "jobs" are
    eng_path=r"C:\Users\jrange14\Desktop\Jobs"
    
    #Look in the directory
    job_name = None
    for entry in os.listdir(eng_path):
        if entry.startswith(job_number):
            job_name = entry
            break
    if job_name is None:
        print("Job number not found")
    else:
        job_path=eng_path+'\\'+job_name
        print(job_path)
    

    【讨论】:

    • 嗨,Balaji,不幸的是,break 声明不起作用。似乎它仍在检查所有文件夹,花费相同的时间。我不知道为什么'break'没有退出循环,似乎我错过了什么。
    • @JorgeRangel 你为什么这么说?
    • 因为获得所需路径所花费的时间相同
    • 这是因为os.listdir 的工作方式。这部分来自文档The list is in arbitrary order 如果需要,请在for loop 中打印entry 并亲自查看。一旦找到888_,循环就会中断
    • 如果我在for 中打印entry,程序将等待与找到所需文件夹相同的时间,然后一键打印所有具有所需文件夹的文件夹路径在最后。
    猜你喜欢
    • 1970-01-01
    • 2021-04-07
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 2013-08-01
    • 2012-02-04
    相关资源
    最近更新 更多