温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python怎么获取指定目录下的所有文件

发布时间:2023-04-21 13:59:36 来源:亿速云 阅读:100 作者:iii 栏目:编程语言

这篇“Python怎么获取指定目录下的所有文件”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python怎么获取指定目录下的所有文件”文章吧。

(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怎么获取指定目录下的所有文件

以上就是关于“Python怎么获取指定目录下的所有文件”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI