Python代码集pathlib应用之如何获取指定目录下的所有文件
作者:EasyWind
时间:2023-04-29
来源:互联网
浏览:0
(1)如下代码,默认递归获取指定目录root_dir下的所有文件,当指定recursive参数为False时,则只获取root_dir目录下的所有文件,不会递归的查找,若指定suffix_tuple参数,则可以获取root_dir目录下的指定后缀文件frompathlibimportPathdefget_all_files(root_dir,recursive=True,suffix_tuple=()):all_files=[]ifPath(root_dir).exists():ifPath(root_d
(1)如下代码,默认递归获取指定目录root_dir下的所有文件,当指定recursive参数为False时,则只获取root_dir目录下的所有文件,不会递归的查找,若指定suffix_tuple参数,则可以获取root_dir目录下的指定后缀文件
from pathlib import Path
def get_all_files(root_dir,recursive=True,suffix_tuple=()):
all_files=[]
if Path(root_dir).exists():
if Path(root_dir).is_dir():
if recursive:
for elem in Path(root_dir).glob("**/*"):
if Path(elem).is_file():
suffix=Path(elem).suffix
if not suffix_tuple:
all_files.append(elem)
else:
if suffix in suffix_tuple:
all_files.append(elem)
else:
for elem in Path(root_dir).iterdir():
if Path(elem).is_file():
suffix=Path(elem).suffix
if not suffix_tuple:
all_files.append(elem)
else:
if suffix in suffix_tuple:
all_files.append(elem)
else:
all_files.append(root_dir)
return all_files(2)具体使用方法如下,即测试代码,具体目录path指定为自己存在的目录
if __name__=="__main__":
path="D:/gitee/oepkgs/mugen/testcases/cli-test/acl/oe_test_acl_defaulr_rule.sh"
for elem in get_all_files(path):
print(elem)
print("-------------------------------------------------")
path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl"
for elem in get_all_files(path):
print(elem)
print("-------------------------------------------------")
path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl"
for elem in get_all_files(path,False):
print(elem)
print("-------------------------------------------------")
path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl"
for elem in get_all_files(path, True,(".sh",)):
print(elem)
print("-------------------------------------------------")
path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl"
for elem in get_all_files(path, True, (".json",)):
print(elem)执行结果如下,第一个当指定path为文件时,则直接将文件作为查询到的返回,最后一个指定.json后缀,因为调试机上没有json文件,所以打印为空

作者最新文章
淘宝闪购“等灯不计时”机制解析:政策、技术与多方协同
2026-09-08 18:00
一加自研电竞三芯P4/G3/T3确认:一加16首发,支持185FPS及9000mAh电池
2026-09-08 16:52
抖音拍摄剪辑教程:从竖屏运镜到卡点成片
2026-09-03 06:05
Excel筛选大于指定数值:操作步骤与结果验证
2026-09-03 06:03
PDF添加文字水印:位置、透明度与字号设置指南
2026-09-03 06:01
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















