python遍历文件夹,指定遍历深度与忽略目录的方法
背景
需要在文件夹中搜索某一文件,找到后返回此文件所在目录。用最常规的os.listdir()方式实现了一版,但执行时报错:递归超过最大深度。于是自己添加了点功能,之所有写此函数是为了让它适应不同的项目,因为有项目要找的文件在第一层,有的在第二层。
函数
功能:在文件夹中查找某一文件,找到后返回True与文件所在目录路径。
参数:filepath,要查找的目录
参数:filename,要查找的文件
扩展1:find_depth,查找时指定递归深度;
扩展2:ignore_path,查找时忽略某些目录;
#!/usr/bin/envpython #coding=utf-8 importos #fromfabric.colorsimport* deffind_file(self,filepath,filename,find_depth=1,ignore_path=['.git','node_modules']): """查找文件""" #printblue("当前查找目录:{},递归层级:{}".format(filepath,find_depth)) #递归深度控制 find_depth-=1 forfile_inos.listdir(filepath): #printcyan("file:{}".format(file_)) ifisfile(join(filepath,file_)): #print"当前文件:{}".format(file_) iffile_==filename: returnTrue,filepath eliffind_depth<=0:#递归深度控制,为0时退出 #printyellow("超出递归深度,忽略!") continue eliffile_inignore_path:#忽略指定目录 #printyellow("此目录在忽略列表中,跳过!") continue else: result,abs_path=self.find_file(filepath=join(filepath,file_), filename=filename, find_depth=find_depth) ifresult: printgreen("找到{}文件,所在路径{}".format(filename,abs_path)) returnresult,abs_path returnFalse,filepath result,filepath=find_build(filepath="/data/deploy/jenkins/data/jobs/sit-zjims-mobile/workspace/",filename="gulpfile.js",find_depth=3)
以上这篇python遍历文件夹,指定遍历深度与忽略目录的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。