广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python代码集pathlib应用之获取指定目录下的所有文件
  • 942
分享到

Python代码集pathlib应用之获取指定目录下的所有文件

Python获取指定目录下的所有文件Python代码集pathlib 2023-03-15 11:03:18 942人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

(1)如下代码,默认递归获取指定目录root_dir下的所有文件,当指定recursive参数为False时,则只获取root_dir目录下的所有文件,不会递归的查找,若指定suff

(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文件,所以打印为空

到此这篇关于python代码集pathlib应用之获取指定目录下的所有文件的文章就介绍到这了,更多相关Python获取指定目录下的所有文件内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python代码集pathlib应用之获取指定目录下的所有文件

本文链接: https://www.lsjlt.com/news/199867.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作