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中selenium实现文件上传所有方法整理总结
Apr 01 Python
Python初学时购物车程序练习实例(推荐)
Aug 08 Python
python根据unicode判断语言类型实例代码
Jan 17 Python
Python实现替换文件中指定内容的方法
Mar 19 Python
python 列表,数组,矩阵两两转换tolist()的实例
Apr 04 Python
解决Django数据库makemigrations有变化但是migrate时未变动问题
May 30 Python
Python 正则表达式匹配字符串中的http链接方法
Dec 25 Python
Python魔法方法功能与用法简介
Apr 04 Python
基于python的BP神经网络及异或实现过程解析
Sep 30 Python
Python迭代器模块itertools使用原理解析
Dec 11 Python
python自动化unittest yaml使用过程解析
Feb 03 Python
Jupyter Notebook打开任意文件夹操作
Apr 14 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代码
2008/04/09 PHP
PHP 远程文件管理,可以给表格排序,遍历目录,时间排序
2009/08/07 PHP
php 多文件上传的实现实例
2016/10/23 PHP
HTML长文本截取含有HTML代码同样适用的两种方法
2013/07/31 Javascript
json数据与字符串的相互转化示例
2013/09/18 Javascript
AngularJs中route的使用方法和配置
2016/02/04 Javascript
JavaScript动态添加css样式和script标签
2016/07/19 Javascript
javascript ASCII和Hex互转的实现方法
2016/12/27 Javascript
XMLHttpRequest对象_Ajax异步请求重点(推荐)
2017/09/28 Javascript
详解webpack运行Babel教程
2018/06/13 Javascript
微信小程序将字符串生成二维码图片的操作方法
2018/07/17 Javascript
javascript实现商品图片放大镜
2019/11/28 Javascript
JS实现TITLE悬停长久显示效果完整示例
2020/02/11 Javascript
使用node-media-server搭建一个简易的流媒体服务器
2021/01/20 Javascript
[27:53]2014 DOTA2华西杯精英邀请赛 5 24 NewBee VS iG
2014/05/26 DOTA
[01:08:48]LGD vs OG 2018国际邀请赛淘汰赛BO3 第三场 8.25
2018/08/29 DOTA
[01:10:24]DOTA2-DPC中国联赛 正赛 VG vs Aster BO3 第一场 2月28日
2021/03/11 DOTA
解决python2.7用pip安装包时出现错误的问题
2017/01/23 Python
wxPython的安装图文教程(Windows)
2017/12/28 Python
Python语言描述随机梯度下降法
2018/01/04 Python
浅析python协程相关概念
2018/01/20 Python
Python使用Pickle库实现读写序列操作示例
2018/06/15 Python
python对象转字典的两种实现方式示例
2019/11/07 Python
python两个_多个字典合并相加的实例代码
2019/12/26 Python
Trip.com香港网站:Ctrip携程旗下,全球最大的网上旅游社之一
2016/08/01 全球购物
意大利在线药房:Farmacia Loreto Gallo
2019/08/09 全球购物
数组越界问题
2015/10/21 面试题
别名指示符是什么
2012/10/08 面试题
园艺师求职信
2014/03/10 职场文书
体育系毕业生自荐信
2014/06/28 职场文书
单位员工收入证明样本
2014/10/09 职场文书
正风肃纪查摆剖析材料
2014/10/10 职场文书
婚前协议书范本两则
2014/10/16 职场文书
2015年暑期社会实践方案
2015/07/14 职场文书
《和时间赛跑》读后感3篇
2019/12/16 职场文书
golang interface判断为空nil的实现代码
2021/04/24 Golang