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

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

相关推荐
仙人球部落38 分钟前
-python-LangGraph框架(3-31-LangGraph 「合并式状态管理」的原理与实践)
开发语言·javascript·python
蜡笔削薪1 小时前
财联支付异地拓展商户的区域限制是否符合监管规定?
大数据·python
印度神油91 小时前
Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
windows·python·ci/cd
chouchuang1 小时前
day-025-面向对象-上
开发语言·python
qetfw1 小时前
CentOS 7 基础环境配置
linux·运维·centos
天空'之城2 小时前
Linux 系统编程 21:守护进程与日志系统全解
linux·系统编程·日志系统·守护进程
l1t2 小时前
用split命令恢复被wget -c命令误追加的zip压缩包
linux
Csvn3 小时前
Python 开发技巧:标准库深度挖掘
后端·python
辉灰笔记3 小时前
MySQL8 意外关机/误移data目录导致服务启动失败 PID报错/权限报错 修复文档
linux·数据库·mysql·centos
li星野3 小时前
二分查找的三重变奏:有序区间、旋转最小值与平方根——从“猜数字”到“向量检索”的思维演化
python