Chinaunix首页 | 论坛 | 博客
  • 博客访问: 375446
  • 博文数量: 26
  • 博客积分: 522
  • 博客等级: 中士
  • 技术积分: 329
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-14 13:49
文章分类

全部博文(26)

文章存档

2015年(2)

2012年(7)

2011年(16)

2009年(1)

我的朋友

分类: Python/Ruby

2015-09-18 16:36:47

要汇总各个目录下文件总数和在目录父级统计汇总子级目录文件总数,编写的一个小脚本。
代码很简洁,大家一看都明白。

点击(此处)折叠或打开

  1. # -*- coding: utf-8 -*-
  2. '''
  3. 仿Linux命令tree生成树形目录结构,
  4. 并汇总当前目录下文件总算

  5. Author: ***
  6. Date: 2015-09-18

  7. '''

  8. import os

  9. def fileCntIn(currPath):
  10.     '''汇总当前目录下文件数'''
  11.     return sum([len(files) for root, dirs, files in os.walk(currPath)])

  12. def dirsTree(startPath):
  13.     '''树形打印出目录结构'''
  14.     for root, dirs, files in os.walk(startPath):
  15.         #获取当前目录下文件数
  16.         fileCount = fileCntIn(root)
  17.         #获取当前目录相对输入目录的层级关系,整数类型
  18.         level = root.replace(startPath, '').count(os.sep)
  19.         #树形结构显示关键语句
  20.         #根据目录的层级关系,重复显示'| '间隔符,
  21.         #第一层 '| '
  22.         #第二层 '| | '
  23.         #第三层 '| | | '
  24.         #依此类推...
  25.         #在每一层结束时,合并输出 '|____'
  26.         indent = '| ' * 1 * level + '|____'
  27.         print '%s%s fileCount:%s' % (indent, os.path.split(root)[1], fileCount)

  28. if __name__ == '__main__':
  29.     path = u"D:\\影像备份\\照片"
  30.     dirsTree(path)
实现结构下图所示

阅读(6559) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~