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

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

相关推荐
TiDB 社区干货传送门7 分钟前
【附操作指南】从 Oceanbase 增量数据同步到 TiDB
linux·服务器·数据库·tidb·oceanbase
沟通qq 8762239657 分钟前
三层电梯的PLC控制实战:从IO表到仿真联调
python
Dxy123931021611 分钟前
python如何去掉字符串中最后一个字符
开发语言·python
红辣椒...12 分钟前
安装next-ai-draw-io
linux·运维·服务器
遇见火星15 分钟前
Linux性能调优:详解磁盘工作流程及性能指标
linux·运维·服务器
专注VB编程开发20年16 分钟前
多线程解压安装ZIP,EXE分析-微软的MSI安装包和 .NET SDK EXE
linux·运维·服务器·microsoft·.net
Dxy123931021628 分钟前
Python类入门:用“汽车工厂”理解面向对象编程
python
拉普拉斯妖10832 分钟前
DAY35 模型可视化与推理
python
无垠的广袤34 分钟前
【启明云端 WT9932S3-Nano 开发板】介绍、环境搭建、工程测试
python·单片机·嵌入式硬件
方安乐36 分钟前
linux常用命令
linux·运维·服务器