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 判断一个进程是否存在
Apr 09 Python
python写的ARP攻击代码实例
Jun 04 Python
mac系统安装Python3初体验
Jan 02 Python
Python及Django框架生成二维码的方法分析
Jan 31 Python
python numpy格式化打印的实例
May 14 Python
python3模块smtplib实现发送邮件功能
May 22 Python
详解python3中tkinter知识点
Jun 21 Python
Python列表(List)知识点总结
Feb 18 Python
浅谈Pandas Series 和 Numpy array中的相同点
Jun 28 Python
django实现web接口 python3模拟Post请求方式
Nov 19 Python
Python通过TensorFLow进行线性模型训练原理与实现方法详解
Jan 15 Python
浅谈Python中的函数(def)及参数传递操作
May 25 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时间戳格式全部汇总 (获取时间、时间戳)
2016/06/13 PHP
php实现基于openssl的加密解密方法
2016/09/30 PHP
漂亮的thinkphp 跳转页封装示例
2019/10/16 PHP
用javascript连接access数据库的方法
2006/11/17 Javascript
JavaScript中的几个关键概念的理解-原型链的构建
2011/05/12 Javascript
javascript阻止浏览器后退事件防止误操作清空表单
2013/11/22 Javascript
jquery获取tagName再进行判断
2014/05/29 Javascript
jquery复选框多选赋值给文本框的方法
2015/01/27 Javascript
jquery分隔Url的param方法(推荐)
2016/05/25 Javascript
confirm确认对话框的实现方法总结
2016/06/17 Javascript
JS重载实现方法分析
2016/12/16 Javascript
bootstrapValidator 重新启用提交按钮的方法
2017/02/20 Javascript
Vue 进阶教程之v-model详解
2017/05/06 Javascript
AngularJS实现的回到顶部指令功能实例
2017/05/17 Javascript
浅谈JS对象添加getter与setter的5种方法
2018/06/09 Javascript
vue文件运行的方法教学
2019/02/12 Javascript
微信小程序下拉框搜索功能的实现方法
2019/07/31 Javascript
Vue实现仿iPhone悬浮球的示例代码
2020/03/13 Javascript
[47:55]Ti4第二日主赛事败者组 NaVi vs EG 1
2014/07/20 DOTA
详解Python3操作Mongodb简明易懂教程
2017/05/25 Python
对python过滤器和lambda函数的用法详解
2019/01/21 Python
Python写一个基于MD5的文件监听程序
2019/03/11 Python
Python中字符串与编码示例代码
2019/05/20 Python
Python第三方包PrettyTable安装及用法解析
2020/07/08 Python
Python如何读写字节数据
2020/08/05 Python
python之语音识别speech模块
2020/09/09 Python
PyQT5速成教程之Qt Designer介绍与入门
2020/11/02 Python
CSS3条纹背景制作的实战攻略
2016/05/31 HTML / CSS
css3动画效果小结(推荐)
2016/07/25 HTML / CSS
周鸿祎:教你写创业计划书
2013/12/30 职场文书
班组长岗位职责
2014/03/03 职场文书
社区工作者个人总结
2015/02/28 职场文书
工程质量保证书
2015/05/09 职场文书
2016年寒假社会实践活动总结
2015/10/10 职场文书
2015年美容师个人工作总结
2015/10/14 职场文书
2016年优秀共产党员先进事迹材料
2016/02/29 职场文书