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

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

相关推荐
程序员-Benothing14 分钟前
Shell 脚本条件判断与流程控制:if for while case 详解
linux·运维·服务器
mounter62516 分钟前
统一安全域:KVM Planes 如何驾驭硬件特权级
linux·安全·linux kernel·kernel
lbb 小魔仙18 分钟前
Python 项目 CI/CD 实战:用 GitHub Actions 搭建自动化测试、覆盖率与发布流水线
python·ci/cd·github
君生我老36 分钟前
Linux动静态库
linux·服务器
西瓜太郎123438 分钟前
request_id 如何串起请求、路由、计费和日志
后端·python
troy12839 分钟前
Python 基础语法(一):变量、数据类型与运算符
java·服务器·python
宵时待雨1 小时前
linux笔记归纳19:网络层协议IP
linux·网络·笔记·网络协议·tcp/ip
用户298698530141 小时前
Python 将 Word 文档转换为图片的实践指南
后端·python·api
弈栈录1 小时前
LangChain Agent 实战:快速构建可调用工具的智能体
python·架构
宸津-代码粉碎机2 小时前
Spring AI 高危CVE漏洞深度复盘|生产禁跑版本汇总+临时防御+修复方案
java·大数据·人工智能·python·spring