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

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

相关推荐
一位代码1 小时前
微软开源项目MarkitDown:一款将pdf/word/ppt等各类文件转换为Markdown格式的python工具
python
jcbut1 小时前
在Linux上安装Kingbase 9
linux·kingbase·人大金仓·电科金仓
小此方2 小时前
Re:Linux系统篇(二十六)进程篇·十一:从底层原理到 exec* 家族:彻底搞懂 Linux 进程程序替换
linux·运维·服务器
Unbelievabletobe8 小时前
解决了股票api接口盘后数据更新慢的问题
大数据·开发语言·python
lpd_lt9 小时前
AI Coding的常用Prompt技巧
python·ai·ai编程
小江的记录本9 小时前
【JVM虚拟机】堆内存分代模型:年轻代(Eden+Survivor)、老年代、元空间Metaspace(附《思维导图》+《面试高频考点清单》)
java·前端·jvm·后端·python·spring·面试
在繁华处9 小时前
Java从零到熟练(三):流程控制
java·开发语言·python
赵民勇9 小时前
fuse-overlayfs命令详解
linux·容器
sulikey9 小时前
个人Linux操作系统学习笔记6 - 操作系统与进程初识
linux·笔记·学习·操作系统·进程
asdzx6710 小时前
使用 Python 快速提取 PDF 中的表格
python·pdf