【发布时间】: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