Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0f18700

Browse files
committed
增加给定目录自定义文件格式和搜索深度的脚本
1 parent c3b29d3 commit 0f18700

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

‎3.search_file_by_suffix.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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)

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
分享一些有用的python代码片,包含如下内容:
44
1. Excel遍历密码自动化解密
55
2. 带进度条下载文件
6-
6+
3. 搜索给定目录下特定格式的文件,支持自定义查找深度
77

88

99
### English Description
1010
Share some useful python snippets, Include the following content:
1111
1. Automatically decrypt password protected excel files.
1212
2. Download the file with the progress bar.
13+
3. Search specific format files from a given directory, support custom search depth.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /