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

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

相关推荐
数智工坊3 小时前
Zotero自建Ubuntu WebDAV附件同步方案(完美解决存储空间不足)
linux·运维·ubuntu
ltl5 小时前
HTTP/3 实战:从 QUIC 到 H3 的完整请求链路
linux
北斗落凡尘5 小时前
LangGraph 入门实战(2)
python·langchain
ltl5 小时前
POSIX 文件锁:flock、fcntl 与 NFS 上的工程陷阱
linux
ltl5 小时前
CUDA 生态:cuBLAS、cuDNN、NCCL、Triton、CUTLASS
linux
饺子大魔王的男人5 小时前
CentOS部署Cockpit:图形化查看系统、日志与服务状态
linux·运维·centos
不会就选b5 小时前
Linux之信号(二)
linux·运维·服务器
ttod_qzstudio5 小时前
Java 常用语法极简通关(五):类与对象——字段、方法、构造器、this 与 static
java·开发语言·python
我是小灰灰吖6 小时前
QT在线安装器使用指南:从下载到配置完整教程
linux·qt·ubuntu
GlueNa2SiO36 小时前
第十八章 Linux故障排查与恢复
linux·服务器·笔记·学习