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发送伪造的arp请求
Jan 09 Python
python脚本实现查找webshell的方法
Jul 31 Python
Python探索之ModelForm代码详解
Oct 26 Python
python文本数据处理学习笔记详解
Jun 17 Python
浅谈tensorflow中张量的提取值和赋值
Jan 19 Python
python tqdm 实现滚动条不上下滚动代码(保持一行内滚动)
Feb 19 Python
python网络编程之五子棋游戏
May 14 Python
pyspark对Mysql数据库进行读写的实现
Dec 30 Python
Spy++的使用方法及下载教程
Jan 29 Python
python中操作文件的模块的方法总结
Feb 04 Python
python基础之错误和异常处理
Oct 24 Python
人工智能深度学习OpenAI baselines的使用方法
May 20 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
WIN98下Apache1.3.14+PHP4.0.4的安装
2006/10/09 PHP
PHP 巧用数组降低程序的时间复杂度
2010/01/01 PHP
解析PHP处理换行符的问题 \r\n
2013/06/13 PHP
调试PHP程序的多种方法介绍
2014/11/06 PHP
PHP魔术方法之__call与__callStatic使用方法
2017/07/23 PHP
PHP实现对数字分隔加千分号的方法
2019/03/18 PHP
PHP使用redis位图bitMap 实现签到功能
2019/10/08 PHP
浅析PHP反序列化中过滤函数使用不当导致的对象注入问题
2020/02/15 PHP
JavaScript(JS) 压缩 / 混淆 / 格式化 批处理工具
2010/12/10 Javascript
js中的preventDefault与stopPropagation详解
2014/01/29 Javascript
jQuery实现的左右移动焦点图效果
2016/01/14 Javascript
jQuery操作属性和样式详解
2016/04/13 Javascript
vue使用keep-alive实现数据缓存不刷新
2017/10/21 Javascript
使用vue制作探探滑动堆叠组件的实例代码
2018/03/07 Javascript
分享Angular http interceptors 拦截器使用(推荐)
2019/11/10 Javascript
[22:20]初生之犊-TI4第5名LGD战队纪录片
2014/08/13 DOTA
安装Python和pygame及相应的环境变量配置(图文教程)
2017/06/04 Python
python+pyqt实现12306图片验证效果
2017/10/25 Python
使用pygame模块编写贪吃蛇的实例讲解
2018/02/05 Python
python 用lambda函数替换for循环的方法
2018/06/09 Python
Python面向对象之接口、抽象类与多态详解
2018/08/27 Python
浅谈pycharm出现卡顿的解决方法
2018/12/03 Python
浅谈Pycharm中的Python Console与Terminal
2019/01/17 Python
在TensorFlow中屏蔽warning的方式
2020/02/04 Python
纯CSS3实现图片无间断轮播效果
2016/08/25 HTML / CSS
HTML 5.1来了 9月份正式发布 更新内容预览
2016/04/26 HTML / CSS
美国休闲服装品牌:J.Crew Factory
2017/03/04 全球购物
运动会通讯稿500字
2014/02/20 职场文书
我爱我家教学反思
2014/05/01 职场文书
政风行风建设责任书
2014/07/23 职场文书
致800米运动员广播稿(10篇)
2014/10/17 职场文书
2014年教研室工作总结
2014/12/06 职场文书
2015国庆节感想
2015/08/04 职场文书
毕业生的自我鉴定表范文
2019/05/16 职场文书
Python中 range | np.arange | np.linspace三者的区别
2022/03/22 Python
css清除浮动clearfix:after的用法详解(附完整代码)
2023/05/21 HTML / CSS