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

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

相关推荐
wacsii2 分钟前
【Linux操作系统】从零手写 mystdio:静态库、动态库制作与第三方链接踩坑
linux·服务器
嵌入式 Linux手记1 小时前
静态库动态库到底差在哪
linux·c语言·嵌入式
Java后端的Ai之路1 小时前
Anthropic 官方文章《Building always-on agents》构建指南
开发语言·网络·python
信安IT租赁1 小时前
小公司服务器的自启动脚本:用 systemd 做成服务,开机自动跑
linux·运维·服务器
陈秋月1 小时前
从一句注释到 root:GoldenEye 靶机通关记录
linux
badhope1 小时前
Agent 说发布成功,文章却 404:我补了 4 张回读收据
后端·python·ai编程
xurileidian2 小时前
第 30 篇 · 边玩边学Python · 猜数字小游戏 把判断循环异常串起来
前端·python·算法
用户96098457922402 小时前
Ubuntu 开发软件全链路美化:VS Code/Cursor/tmux/delta/fzf 实战
linux
南棱笑笑生2 小时前
20261127在RK3576的Android14系统下适配2个以太网卡RTL821F-CG【无外部晶振模式】
linux·服务器·数据库·驱动开发
Julien20042 小时前
管理机密(二)
linux·运维·服务器·学习方法