当前位置: 首页 > news >正文

Python:打印目录下每层的文件总数

代码如下:

import osclass FileCount(object):def __init__(self,root_path: str):self.root_path = root_pathself._count = Noneself._file_count = Noneself.children = []def get_count(self):if self._count is None:self._count = 0self._file_count = 0for 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 += 1self._file_count += 1return self._countdef get_file_count(self):if self._file_count is None:self.get_count()return self._file_countdef 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 argparseparser = 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
打印出来的效果如下:

test_folder --- 6
├──	folder_1 --- 2
│	├──	folder_1 --- 1
│	│	└──	files 1
│	└──	files 1
├──	folder_2 --- 2
│	└──	files 2
└──	files 2

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

http://www.lryc.cn/news/173521.html

相关文章:

  • LVS-NAT模式
  • 【神印王座】龙皓晨竟然上了头版头条!内容违背,新闻真实性原则
  • C++之类和函数权限访问总结(二百二十七)
  • 手动部署 OceanBase 集群
  • 【操作系统笔记十二】Linux常用基础命令
  • Compose LazyColumn 对比 RecyclerView ,谁的性能更好?
  • [python 刷题] 49 Group Anagrams
  • vue+element plus 使用table组件,清空用户的选择项
  • 改写软件-怎么选择改写软件
  • gateway之跨域处理
  • uniapp 实现不同用户展示不同的tabbar(底部导航栏)
  • 线性归一化是什么,用python实现数据的线性归一化
  • 超级好用绘图工具(Draw.io+Github)
  • 全国职业技能大赛云计算--高职组赛题卷③(私有云)
  • Redis SCAN命令操作实战(详细)
  • 计网第五章(运输层)(六)(TCP可靠传输的实现)
  • 酒店外卖小程序商城的作用是什么
  • 居家养老一键通的功能
  • 海外代理IP是什么?如何使用?
  • mmdetection v3避坑
  • 备份服务器数据库并保存到Git仓库
  • 尚硅谷wepack课程学习笔记
  • c++模版元编程-可变参数模版
  • pcl--第十节 点云曲面重建
  • 【力扣-每日一题】2560. 打家劫舍 IV
  • vue简单案例----小张记事本
  • 爬虫获取接口数据
  • 私域流量的变现方式,你知道多少?
  • Webpack配置entry修改入口文件或打包多个文件
  • Mac mini2014(装的windows)重装回MacOS