Python显示目录的树形结构

来源:互联网 发布:阿里云数据盘 编辑:程序博客网 时间:2024/04/29 20:33
转自http://blog.chinaunix.net/uid-21374062-id-5198995.html
Python显示目录的树形结构
# -*- coding: utf-8 -*- '''仿Linux命令tree生成树形目录结构,并汇总当前目录下文件总算Author: ***Date: 2015-09-18'''import osdef fileCntIn(currPath):    '''汇总当前目录下文件数'''    return sum([len(files) for root, dirs, files in os.walk(currPath)])def dirsTree(startPath):    '''树形打印出目录结构'''    for root, dirs, files in os.walk(startPath):        #获取当前目录下文件数        fileCount = fileCntIn(root)        #获取当前目录相对输入目录的层级关系,整数类型        level = root.replace(startPath, '').count(os.sep)        #树形结构显示关键语句        #根据目录的层级关系,重复显示'| '间隔符,        #第一层 '| '        #第二层 '| | '        #第三层 '| | | '        #依此类推...        #在每一层结束时,合并输出 '|____'        indent = '| ' * 1 * level + '|____'        print '%s%s fileCount:%s' % (indent, os.path.split(root)[1], fileCount)if __name__ == '__main__':    path = u"D:\\影像备份\\照片"    dirsTree(path)



实现结构下图所示

0 0
原创粉丝点击