zoukankan      html  css  js  c++  java
  • python 递归查找统计某个文件夹下的文件数量[转]

    python 递归查找统计某个文件夹下的文件数量[转]

    link: https://blog.csdn.net/fscanf_fread/article/details/106154227

    操作系统下的文件夹具有递归属性,主文件夹可以包含子文件和子文件夹,每个子文件夹下又可以包含更多的文件和文件夹, 当我们想要统计当前文件夹下所有的文件数量时,用递归的方法可以容易的实现。

     

    用tree /f /a命令查看一下文件夹的目录结构

    C:\TEST

    | test1.txt

    | test2.txt

    | test3.txt

    |

    \---sub_test

    test4.txt

    test5.txt

     

    python 代码实现

    import os

     

    def countFiles(root_path):

        assert os.path.exists(root_path)

        total_files = 0

        item_list = os.listdir(root_path)

        if len(item_list) == 0:

            return 0

        for item in item_list:

            next_path = os.path.join(root_path, item)

            if os.path.isfile(next_path):

                total_files += 1

            else:

                total_files += countFiles(next_path)

     

        return total_files

     

     

    if __name__ == '__main__':

        root_path = 'C:\\test'

        num = countFiles(root_path)

        print(f'total files: {num}')

     

    • 输出结果

    total files: 5

  • 相关阅读:
    Block的强强引用问题(循环引用)
    自己封装的下载方法
    MJRefresh上拉刷新下拉加载
    JavaScript 模块的循环加载
    webpack使用require注意事项
    console.log高级用法
    path.resolve()和path.join()的区别
    深入理解react
    react children技巧总结
    揭秘css
  • 原文地址:https://www.cnblogs.com/xiexiaokui/p/15532990.html
Copyright © 2011-2022 走看看