python实现目录树生成示例


Posted in Python onMarch 28, 2014
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import optparse
LOCATION_NONE     = 'NONE'
LOCATION_MID      = 'MID'
LOCATION_MID_GAP  = 'MID_GAP'
LOCATION_TAIL     = 'TAIL'
LOCATION_TAIL_GAP = 'TAIL_GAP'
Notations = {
    LOCATION_NONE: '',
    LOCATION_MID: '├─',
    LOCATION_MID_GAP: '│  ',
    LOCATION_TAIL: '└─',
    LOCATION_TAIL_GAP: '    '
}
class Node(object):
    def __init__(self, name, depth, parent=None, location=LOCATION_NONE):
        self.name = name
        self.depth = depth
        self.parent = parent
        self.location = location
        self.children = []
    def __str__(self):
        sections = [self.name]
        parent = self.has_parent()
        if parent:
            if self.is_tail():
                sections.insert(0, Notations[LOCATION_TAIL])
            else:
                sections.insert(0, Notations[LOCATION_MID])
            self.__insert_gaps(self, sections)
        return ''.join(sections)
    def __insert_gaps(self, node, sections):
        parent = node.has_parent()
        # parent exists and parent's parent is not the root node
        if parent and parent.has_parent():
            if parent.is_tail():
                sections.insert(0, Notations[LOCATION_TAIL_GAP])
            else:
                sections.insert(0, Notations[LOCATION_MID_GAP])
            self.__insert_gaps(parent, sections)
    def has_parent(self):
        return self.parent
    def has_children(self):
        return self.children
    def add_child(self, node):
        self.children.append(node)
    def is_tail(self):
        return self.location == LOCATION_TAIL
class Tree(object):
    def __init__(self):
        self.nodes = []
    def debug_print(self):
        for node in self.nodes:
            print(str(node) + '/')
    def write2file(self, filename):
        try:
            with open(filename, 'w') as fp:
                fp.writelines(str(node) + '/\n'
                              for node in self.nodes)
        except IOError as e:
            print(e)
            return 0
        return 1
    def build(self, path):
        self.__build(path, 0, None, LOCATION_NONE)
    def __build(self, path, depth, parent, location):
        if os.path.isdir(path):
            name = os.path.basename(path)
            node = Node(name, depth, parent, location)
            self.add_node(node)
            if parent:
                parent.add_child(node)
            entries = self.list_folder(path)
            end_index = len(entries) - 1
            for i, entry in enumerate(entries):
                childpath = os.path.join(path, entry)
                location = LOCATION_TAIL if i == end_index else LOCATION_MID
                self.__build(childpath, depth + 1, node, location)
    def list_folder(self, path):
        """Folders only."""
        return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
        # for entry in os.listdir(path):
        #     childpath = os.path.join(path, entry)
        #     if os.path.isdir(childpath):
        #         yield entry
    def add_node(self, node):
        self.nodes.append(node)
def _parse_args():
    parser = optparse.OptionParser()
    parser.add_option(
        '-p', '--path', dest='path', action='store', type='string',
        default='./', help='the path to generate the tree [default: %default]')
    parser.add_option(
        '-o', '--out', dest='file', action='store', type='string',
        help='the file to save the result [default: pathname.trees]')
    options, args = parser.parse_args()
    # positional arguments are ignored
    return options
def main():
    options = _parse_args()
    path = options.path
    if not os.path.isdir(path):
        print('%s is not a directory' % path)
        return 2
    if not path or path == './':
        filepath = os.path.realpath(__file__)  # for linux
        path = os.path.dirname(filepath)
    tree = Tree()
    tree.build(path)
    # tree.debug_print()
    if options.file:
        filename = options.file
    else:
        name = os.path.basename(path)
        filename = '%s.trees' % name
    return tree.write2file(filename)
if __name__ == '__main__':
    import sys
    sys.exit(main())

运行效果

gtest_start/
├─build/
├─lib/
│  └─gtest/
├─output/
│  ├─primer/
│  │  ├─Debug/
│  │  │  ├─lib/
│  │  │  └─obj/
│  │  └─Release/
│  │      ├─lib/
│  │      └─obj/
│  └─thoughts/
│      ├─Debug/
│      │  ├─lib/
│      │  └─obj/
│      └─Release/
│          ├─lib/
│          └─obj/
├─src/
│  ├─primer/
│  └─thoughts/
├─test/
│  ├─primer/
│  └─thoughts/
├─third_party/
│  └─gtest/
└─tools/
Python 相关文章推荐
python脚本实现统计日志文件中的ip访问次数代码分享
Aug 06 Python
实例讲解Python中的私有属性
Aug 21 Python
python制作websocket服务器实例分享
Nov 20 Python
Python标准库06之子进程 (subprocess包) 详解
Dec 07 Python
Sanic框架配置操作分析
Jul 17 Python
Django CSRF跨站请求伪造防护过程解析
Jul 31 Python
python datetime中strptime用法详解
Aug 29 Python
window7下的python2.7版本和python3.5版本的opencv-python安装过程
Oct 24 Python
Pycharm创建项目时如何自动添加头部信息
Nov 14 Python
使用python 将图片复制到系统剪贴中
Dec 13 Python
如何使用Python破解ZIP或RAR压缩文件密码
Jan 09 Python
Python ATM功能实现代码实例
Mar 19 Python
python改变日志(logging)存放位置的示例
Mar 27 #Python
使用python删除nginx缓存文件示例(python文件操作)
Mar 26 #Python
python实现ip查询示例
Mar 26 #Python
python fabric实现远程操作和部署示例
Mar 25 #Python
python基础教程之数字处理(math)模块详解
Mar 25 #Python
python操作摄像头截图实现远程监控的例子
Mar 25 #Python
python基础教程之字典操作详解
Mar 25 #Python
You might like
BBS(php & mysql)完整版(五)
2006/10/09 PHP
PHP 选项及相关信息函数库
2006/12/04 PHP
PHP5函数小全(分享)
2013/06/06 PHP
yii操作session实例简介
2014/07/31 PHP
扩展javascript的Date方法实现代码(prototype)
2010/11/20 Javascript
关于javascript中的typeof和instanceof介绍
2012/12/04 Javascript
Js 代码中,ajax请求地址后加随机数防止浏览器缓存的原因
2013/05/07 Javascript
js将控件隐藏及display属性的使用介绍
2013/12/30 Javascript
js控制href内容的连接内容的变化示例
2014/04/30 Javascript
jQuery知识点整理
2015/01/30 Javascript
Javascript aop(面向切面编程)之around(环绕)分析
2015/05/01 Javascript
javascript实现图片轮播效果
2016/01/20 Javascript
在element-ui的select下拉框加上滚动加载
2019/04/18 Javascript
详解使用JWT实现单点登录(完全跨域方案)
2019/08/02 Javascript
微信小程序录音实现功能并上传(使用node解析接收)
2020/02/26 Javascript
[01:26]神话结束了,却也刚刚开始——DOTA2新英雄玛尔斯驾临战场
2019/03/10 DOTA
Python的函数嵌套的使用方法
2014/01/24 Python
Python contextlib模块使用示例
2015/02/18 Python
使用Python发送各种形式的邮件的方法汇总
2015/11/09 Python
Python实现MySQL操作的方法小结【安装,连接,增删改查等】
2017/07/12 Python
pygame实现俄罗斯方块游戏(基础篇2)
2019/10/29 Python
使用Filters滤镜弥补CSS3的跨浏览器问题以及兼容低版本IE
2013/01/23 HTML / CSS
HTML5单页面手势滑屏切换原理分析
2017/07/10 HTML / CSS
东南亚地区最大的购物网站Lazada新加坡站点:Lazada.sg
2016/07/17 全球购物
泰国折扣酒店预订:Hotels2Thailand
2018/03/20 全球购物
毕业生找工作的自我评价
2013/10/18 职场文书
英文自荐信
2013/12/19 职场文书
文明青少年标兵事迹材料
2014/01/28 职场文书
2014年信贷员工作总结
2014/11/18 职场文书
2014矛盾纠纷排查调处工作总结
2014/12/09 职场文书
2015年财务试用期工作总结
2014/12/24 职场文书
晚会开幕词
2015/01/28 职场文书
初中生物教学随笔
2015/08/15 职场文书
少先大队干部竞选稿
2015/11/20 职场文书
MySQL的全局锁和表级锁的具体使用
2021/08/23 MySQL
java如何实现socket连接方法封装
2021/09/25 Java/Android