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

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

相关推荐
Mr.H012715 分钟前
多线程文件拷贝:从原理到实现的完整指南
linux·运维
2501_9411118216 分钟前
使用Scikit-learn进行机器学习模型评估
jvm·数据库·python
橘子真甜~34 分钟前
C/C++ Linux网络编程5 - 网络IO模型与select解决客户端并发连接问题
linux·运维·服务器·c语言·开发语言·网络·c++
小呀小萝卜儿39 分钟前
2025-11-14 学习记录--Python-使用sklearn+检测 .csv 文件的编码+读取 .csv 文件
python·学习
oushaojun21 小时前
Linux内核KGDB进阶:源码级调试实战演练(转)
linux·运维·kgdb
java1234_小锋1 小时前
[免费]基于python的Flask+Vue医疗疾病数据分析大屏可视化系统(机器学习随机森林算法+requests)【论文+源码+SQL脚本】
python·机器学习·数据分析·flask·疾病数据分析
船长㉿1 小时前
vim常用命令
linux·编辑器·vim
大聪明-PLUS2 小时前
Linux 系统中的 CPU。文章 2:平均负载
linux·嵌入式·arm·smarc
listhi5202 小时前
使用SCP命令在CentOS 7上向目标服务器传输文件
linux·服务器·centos
MediaTea2 小时前
Python 第三方库:cv2(OpenCV 图像处理与计算机视觉库)
开发语言·图像处理·python·opencv·计算机视觉