Python:打印目录下每层的文件总数

代码如下:

python 复制代码
import os


class FileCount(object):
    def __init__(self,
                 root_path: str):
        self.root_path = root_path
        self._count = None
        self._file_count = None
        self.children = []

    def get_count(self):
        if self._count is None:
            self._count = 0
            self._file_count = 0
            for child_name in os.listdir(self.root_path):
                child_path = os.path.join(self.root_path, child_name)
                if os.path.isdir(child_path):
                    child = FileCount(child_path)
                    self.children.append(child)
                    self._count += child.get_count()
                else:
                    self._count += 1
                    self._file_count += 1
        return self._count

    def get_file_count(self):
        if self._file_count is None:
            self.get_count()
        return self._file_count

    def print_count(self,
                    indent: int = 0):
        count_prefix = ''
        for i in range(indent - 1):
            count_prefix += '│\t'
        if indent > 0:
            count_prefix += '├──\t'
        print(count_prefix + os.path.basename(self.root_path), '---', self.get_count())

        for child in self.children:
            child.print_count(indent + 1)

        child_count_prefix = ''
        for i in range(indent):
            child_count_prefix += '│\t'
        child_count_prefix += '└──\t'
        print(child_count_prefix + 'files', self.get_file_count())


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--root_path', type=str, default='./', help='Root path.')
    args = parser.parse_args()

    count = FileCount(args.root_path)
    count.print_count()

根目录通过命令行参数设置,例如
python print_file_sum.py -p D:\Temp\test_folder

打印出来的效果如下:

bash 复制代码
test_folder --- 6
├──	folder_1 --- 2
│	├──	folder_1 --- 1
│	│	└──	files 1
│	└──	files 1
├──	folder_2 --- 2
│	└──	files 2
└──	files 2

每一行的数字代表该级目录下的文件总数(包括子目录),下面还会给出每个子目录的统计情况,以及非目录文件数量。

相关推荐
weixin_446260855 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao6 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
DFT计算杂谈6 小时前
无 Root 权限在 Tesla K80 零门槛部署 DeepSeek 大模型
linux·服务器·网络·数据库·机器学习
qetfw6 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具
用户8356290780517 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
Zhang~Ling7 小时前
从 fopen 到 struct file:从零开始拆解 Linux 文件 I/O
linux·运维·服务器
一次旅行7 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化
DeeplyMind7 小时前
Linux 深入 per-VMA lock:Linux 缺页路径如何摆脱 mmap_lock
linux·per-vma lock
天天爱吃肉82187 小时前
【电源拆解:跟着问答逐一认识开关适配器PCB元器件】
大数据·人工智能·python·功能测试·嵌入式硬件·汽车
_Jimmy_7 小时前
AI应用开发工程师面试题库
人工智能·python·深度学习·机器学习·知识图谱