美文网首页
Python 打印目录树

Python 打印目录树

作者: 我不懂我不懂a | 来源:发表于2022-09-09 12:04 被阅读0次
    # coding=utf-8
    import os.path
    import sys
    import time
    
    link1 = "─┬─"
    link2 = "├──"
    link3 = "───"
    link4 = "└──"
    link5 = " │ "
    link6 = "   "
    link7 = "│  "
    
    
    class File(object):
        def __init__(self, abs_path, name, children=[]):
            self.abs_path = abs_path
            self.name = name
            self.children = children
            self.next = None
    
        def __repr__(self) -> str:
            return str({'name': self.name,
                        'children': self.children
                        })
    
    
    def create_path(parent, file):
        return parent + os.sep + file
    
    
    def sub_dirs(path):
        return [x for x in os.listdir(path) if os.path.isdir(create_path(path, x))]
    
    
    def sub_dirs_abs(path):
        return [create_path(path, x) for x in os.listdir(path) if os.path.isdir(create_path(path, x))]
    
    
    def dir_tree(path):
        parent = File(path, os.path.basename(path), [])
        dirs = sub_dirs_abs(path)
        for dir in dirs:
            kid = dir_tree(dir)
            parent.children.append(kid)
    
        for i in range(len(parent.children) - 1):
            parent.children[i].next = parent.children[i + 1]
    
        return parent
    
    
    def space(num=0):
        return " " * num
    
    
    def print_prefix():
        pass
    
    
    def print_dir_tree(dir, link='', deep=0, prefix_print=''):
        print(prefix_print, end="")
        print(link, end="")
        print(dir.name)
    
        if dir.next:
            prefix_print += link7
        else:
            prefix_print += link6
    
        for i in range(len(dir.children) - 1):
            print_dir_tree(dir.children[i], link2, deep + 1, prefix_print)
        if len(dir.children) >= 1:
            print_dir_tree(dir.children[-1], link4, deep + 1, prefix_print)
    
    
    def main(argv):
        base_path = argv[1] if len(argv) >= 2 else os.path.abspath('.')
        root = dir_tree(base_path)
        print_dir_tree(root)
    
    
    if __name__ == '__main__':
        start = time.time()
        main(sys.argv)
        end = time.time()
        print("print dir tree cost {:.2f}s".format(end - start))
    
    

    相关文章

      网友评论

          本文标题:Python 打印目录树

          本文链接:https://www.haomeiwen.com/subject/smdtortx.html