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 分钟前
【Python基础】从变量到面向对象:打通 Python 入门核心语法
开发语言·python
财经资讯数据_灵砚智能5 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年6月7日
大数据·人工智能·python·ai·信息可视化·自然语言处理·灵砚智能
凡人叶枫7 分钟前
Effective C++ 条款05:了解 C++ 默默编写并调用哪些函数
java·linux·开发语言·c++·effective c++·编程范式
星川皆无恙21 分钟前
Python豆瓣电影数据分析可视化系统:爬虫采集+数据清洗+可视化大屏完整项目
人工智能·爬虫·python·数据分析
ttwuai23 分钟前
XYGo Admin 扩展开发:WebSocket 事件注册与实时推送实战
python·websocket·网络协议·golang·后台框架
Metaphor69224 分钟前
使用 Python 旋转 PDF 页面
python·pdf
2601_9611940226 分钟前
考研资料电子版|下载|pdf
java·python·考研·eclipse·django·pdf·pygame
ftf拿破仑26 分钟前
嵌入式面试高频问题
linux·面试
盼小辉丶29 分钟前
OpenCV-Python实战(26)——复杂场景下的实时物体检测与跟踪
python·opencv·计算机视觉