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

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

相关推荐
nanawinona1 分钟前
先跑通小流程,再让 AI 和 Python 承接复杂量化
人工智能·python
DeepVisionary3 分钟前
8 月 20 款大模型同台:OpenAI 拆出三档家族,IBM 押注 512K 密集推理,Meta 回头开源 30B
python·自动化
未若君雅裁3 分钟前
自定义中间件:Node-style 与 Wrap-style 钩子全解析
python·中间件·langchain
奈斯先生Vector5 分钟前
本地图片识别怎么接入多模态 AI?用 Python API 理解 GPT-4o Vision 的真实工作流
开发语言·人工智能·windows·python·网络协议·http·aigc
高亦真9 分钟前
今天是学习嵌入式的第33天
linux·学习·算法
测试老哥11 分钟前
Pytest 之assert断言的使用
自动化测试·软件测试·python·测试工具·测试用例·pytest·接口测试
cuijiecheng201819 分钟前
Rocky Linux 安装 libltc、ltc-tools 和 ltcdump
linux
BlueAsia_Lab19 分钟前
BQB 认证执行标准是什么?核心条款通俗解读
linux·运维·网络
小小、码农23 分钟前
【网络】套接字(Socket)编程——TCP版
linux·服务器·网络·c++·网络协议·tcp/ip
2601_9563198824 分钟前
先把交易想法说清,再让 Python 承接
人工智能·python