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多线程中阻塞(join)与锁(Lock)使用误区解析
Apr 27 Python
python实现守护进程、守护线程、守护非守护并行
May 05 Python
TensorFlow的权值更新方法
Jun 14 Python
Python从Excel中读取日期一列的方法
Nov 28 Python
解决python3.5 正常安装 却不能直接使用Tkinter包的问题
Feb 22 Python
TensorFlow——Checkpoint为模型添加检查点的实例
Jan 21 Python
Django使用list对单个或者多个字段求values值实例
Mar 31 Python
基于pycharm实现批量修改变量名
Jun 02 Python
8种常用的Python工具
Aug 05 Python
浅析关于Keras的安装(pycharm)和初步理解
Oct 23 Python
Python实现随机爬山算法
Jan 29 Python
matplotlib之pyplot模块坐标轴标签设置使用(xlabel()、ylabel())
Feb 22 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
PHP实现的交通银行网银在线支付接口ECSHOP插件和使用例子
2014/05/10 PHP
PHP获取客户端真实IP地址的5种情况分析和实现代码
2014/07/08 PHP
php多次include后导致全局变量global失效的解决方法
2015/02/28 PHP
javascript计算用户打开网页的停留时间
2014/01/09 Javascript
使用jQuery中的when实现多个AJAX请求对应单个回调的例子分享
2014/04/23 Javascript
jQuery数据缓存用法分析
2015/02/20 Javascript
js实现仿QQ秀换装效果的方法
2015/03/04 Javascript
jQuery插件StickUp实现网页导航置顶
2015/04/12 Javascript
jQuery中$(function() {});问题详解
2015/08/10 Javascript
JQuery实现左右滚动菜单特效
2015/09/28 Javascript
Bootstrap 表单验证formValidation 实现远程验证功能
2017/05/17 Javascript
javascript流程控制语句集合
2017/09/18 Javascript
Vue2.0学习之详解Vue 组件及父子组件通信
2017/12/12 Javascript
JS获取url参数,JS发送json格式的POST请求方法
2018/03/29 Javascript
vue 左滑删除功能的示例代码
2019/01/28 Javascript
浅谈一种让小程序支持JSX语法的新思路
2019/06/16 Javascript
vue实现抽屉弹窗效果
2020/11/15 Javascript
[01:02:48]2018DOTA2亚洲邀请赛小组赛 A组加赛 Newbee vs Liquid
2018/04/03 DOTA
python中定义结构体的方法
2013/03/04 Python
python实现时间o(1)的最小栈的实例代码
2018/07/23 Python
Django使用AJAX调用自己写的API接口的方法
2019/03/06 Python
PYQT5实现控制台显示功能的方法
2019/06/25 Python
Pytorch GPU显存充足却显示out of memory的解决方式
2020/01/13 Python
Python文件操作方法详解
2020/02/09 Python
英国剑桥包官网:The Cambridge Satchel Company
2016/08/01 全球购物
JAVA中的关键字有什么特点
2014/03/07 面试题
大专生简历的自我评价
2013/11/26 职场文书
护理专业自我鉴定
2014/01/30 职场文书
四群教育工作实施方案
2014/03/26 职场文书
娱乐节目策划方案
2014/06/10 职场文书
软环境建设心得体会
2014/09/09 职场文书
股东授权委托书范文
2014/09/13 职场文书
邀请书格式范文
2015/02/02 职场文书
2015年销售部工作总结范文
2015/04/27 职场文书
感恩教育主题班会
2015/08/12 职场文书
在CSS中使用when/else的方法
2022/01/18 HTML / CSS