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中Class类用法实例分析
Nov 12 Python
Python实现Linux命令xxd -i功能
Mar 06 Python
Python设计足球联赛赛程表程序的思路与简单实现示例
Jun 28 Python
Python基于matplotlib绘制栈式直方图的方法示例
Aug 09 Python
python 3利用Dlib 19.7实现摄像头人脸检测特征点标定
Feb 26 Python
python如何把嵌套列表转变成普通列表
Mar 20 Python
使用Template格式化Python字符串的方法
Jan 22 Python
将Pytorch模型从CPU转换成GPU的实现方法
Aug 19 Python
python 实现线程之间的通信示例
Feb 14 Python
Python如何实现FTP功能
May 28 Python
pycharm中如何自定义设置通过“ctrl+滚轮”进行放大和缩小实现方法
Sep 16 Python
Python实现打乒乓小游戏
Sep 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+SQLite存储方案
2010/09/04 PHP
PHP逐行输出(ob_flush与flush的组合)
2012/02/04 PHP
PHP基于数组实现的分页函数实例
2014/08/20 PHP
PHP数据对象PDO操作技巧小结
2016/09/27 PHP
PHP连接sftp并下载文件的方法教程
2018/08/26 PHP
jQuery1.9.1针对checkbox的调整方法(prop)
2014/05/01 Javascript
JavaScript基本语法讲解
2015/06/03 Javascript
JavaScript SHA512&SHA256加密算法详解
2015/08/11 Javascript
JS实现仿雅虎首页快捷登录入口及导航模块效果
2015/09/19 Javascript
javascript函数命名的三种方式及区别介绍
2016/03/22 Javascript
javascript实现不同颜色Tab标签切换效果
2016/04/27 Javascript
jQuery Easyui 验证两次密码输入是否相等
2016/05/13 Javascript
Vue.js实现一个自定义分页组件vue-paginaiton
2016/09/05 Javascript
基于jQuery实现滚动切换效果
2016/12/02 Javascript
js addDqmForPP给标签内属性值加上双引号的函数
2016/12/24 Javascript
微信小程序 增、删、改、查操作实例详解
2017/01/13 Javascript
解决nodejs的npm命令无反应的问题
2018/05/17 NodeJs
微信小程序购物车、父子组件传值及calc的注意事项总结
2018/11/14 Javascript
Vue开发之封装分页组件与使用示例
2019/04/25 Javascript
[01:52]2020年DOTA2 TI10夏季活动预告片
2020/07/15 DOTA
Python实现视频下载功能
2017/03/14 Python
Pandas标记删除重复记录的方法
2018/04/08 Python
浅析PHP与Python进行数据交互
2018/05/15 Python
Python3实现转换Image图片格式
2018/06/21 Python
Python object类中的特殊方法代码讲解
2020/03/06 Python
Python如何使用27行代码绘制星星图
2020/07/20 Python
CSS3制作皮卡丘动画壁纸的示例
2020/11/02 HTML / CSS
在html5的Canvas上绘制椭圆的几种方法总结
2013/01/07 HTML / CSS
敬老文明号事迹材料
2014/01/16 职场文书
银行竞聘报告范文
2014/11/06 职场文书
关于迟到的检讨书
2015/05/06 职场文书
pandas DataFrame.shift()函数的具体使用
2021/05/24 Python
星际争霸 Light vs Action 一场把教主看到鬼畜的比赛
2022/04/01 星际争霸
Netflix《海贼王》真人版剧集多张片场照曝光
2022/04/04 日漫
从零开始在Centos7上部署SpringBoot项目
2022/04/07 Servers
centos环境下nginx高可用集群的搭建指南
2022/07/23 Servers