• 技术文章 >后端开发 >Python教程

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

    WBOYWBOY2023-04-19 12:37:03转载88

    (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应用之如何获取指定目录下的所有文件的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除
    专题推荐:Python pathlib
    上一篇:Python五连冠!2021年 IEEE编程语言排行榜出炉! 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • 学习Python实现自动驾驶系统• Python继续霸占TIOBE编程语言排行榜榜首!• Python虚拟机中浮点数的实现原理是什么?• 如何使用Python的pathlib模块处理文件路径?• Python生产者与消费者模型的优势是什么?
    1/1

    PHP中文网