1
+ # -*- coding: utf-8 -*-
2
+ __author__ = "eason"
3
+ import os
4
+
5
+
6
+ def get_file_by_suffix (folder : str , suffix : str = None , deep : int = None )-> str :
7
+ """
8
+ 生成器函数,返还给定目录中指定格式的文件路径
9
+ :param folder: 要遍历的根目录
10
+ :param suffix: 要查找的指定格式,小写,如果有多种格式用逗号隔开,例如"pdf,zip,rar"
11
+ :param deep: 查找深度,默认全部查找,0为当前目录
12
+ :return:
13
+ """
14
+ for parent , dirnames , filenames in os .walk (folder ):
15
+ # print("当前目录:", parent)
16
+ # print("下层文件夹名字:", dirnames)
17
+ for filename in filenames :
18
+ file_location = os .path .join (parent , filename )
19
+ # print("相对深度:", parent.count("\\")-folder.count("\\"))
20
+ if suffix :
21
+ match_list = suffix .split ("," )
22
+ for suffix in match_list :
23
+ if deep is not None :
24
+ if (parent .count ("\\ " )- folder .count ("\\ " )) <= deep and file_location .endswith (suffix ):
25
+ yield file_location
26
+ else :
27
+ pass
28
+ elif file_location .endswith (suffix ):
29
+ yield file_location
30
+ else :
31
+ pass
32
+ elif deep is not None :
33
+ if (parent .count ("\\ " ) - folder .count ("\\ " )) <= deep :
34
+ yield file_location
35
+ else :
36
+ yield file_location
37
+
38
+
39
+ if __name__ == "__main__" :
40
+ for file in get_file_by_suffix (folder = r"C:\Users\eason\Desktop\test" , suffix = "xls,xlsx" ):
41
+ print (file )
0 commit comments