背景
需要在文件夾中搜索某一文件,找到后返回此文件所在目錄。用最常規的os.listdir()方式實現了一版,但執行時報錯:遞歸超過最大深度。于是自己添加了點功能,之所有寫此函數是為了讓它適應不同的項目,因為有項目要找的文件在第一層,有的在第二層。
函數
功能:在文件夾中查找某一文件,找到后返回True與文件所在目錄路徑。
參數:filepath, 要查找的目錄
參數:filename, 要查找的文件
擴展1:find_depth, 查找時指定遞歸深度;
擴展2:ignore_path, 查找時忽略某些目錄;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#!/usr/bin/env python # coding=utf-8 import os # from fabric.colors import * def find_file( self , filepath, filename, find_depth = 1 , ignore_path = [ '.git' , 'node_modules' ]): """查找文件""" # print blue("當前查找目錄:{},遞歸層級:{}".format(filepath, find_depth)) # 遞歸深度控制 find_depth - = 1 for file_ in os.listdir(filepath): # print cyan("file: {}".format(file_)) if isfile(join(filepath, file_)): # print "當前文件:{}".format(file_) if file_ = = filename: return True , filepath elif find_depth < = 0 : # 遞歸深度控制, 為0時退出 # print yellow("超出遞歸深度,忽略!") continue elif file_ in ignore_path: # 忽略指定目錄 # print yellow("此目錄在忽略列表中,跳過!") continue else : result, abs_path = self .find_file(filepath = join(filepath, file_), filename = filename, find_depth = find_depth) if result: print green( "找到{}文件,所在路徑{}" . format (filename, abs_path)) return result, abs_path return False , filepath result, filepath = find_build(filepath = "/data/deploy/jenkins/data/jobs/sit-zjims-mobile/workspace/" , filename = "gulpfile.js" , find_depth = 3 ) |
以上這篇python遍歷文件夾,指定遍歷深度與忽略目錄的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/yu12377/article/details/77965905