• 【Python】用文本打印树


    From:http://zhidao.baidu.com/link?url=O8U5TynGBMojDw2iFhlghPPf5_ZE1X8CAQMrK19pv-KxhvKCc6Z2yzsoQaukgN2haYudVO7Hg3c0ZvNm8ALcY_

    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
     
    def print_tree(tree):
        buff = ['ROOT/']
        _print_tree(tree, buff, '', 0)
        print('
    '.join(buff))
     
    def _print_tree(tree, buff, prefix, level):
        count = len(tree)
        for k, v in tree.items():
            count -= 1
            if v:
                buff.append('%s +- %s/' % (prefix, k))
                if count > 0:
                    _print_tree(v, buff, prefix + ' |  ', level + 1)
                else:
                    _print_tree(v, buff, prefix + '    ', level + 1)
            else:
                buff.append('%s +- %s' % (prefix, k))
     
    def test():
        tree = {
            'bin': { 'bash': None, 'cat': None, 'cp': None, },
            'etc': {
                'init.d': { 'apache2':None, 'slapd':None, 'sshd':None, },
                'passwd': None,
                'hosts': None,
            },
            'var': {
                'log': {
                    'apache2': { 'accesslog':None, 'errorlog': None, },
                },
            },
        }
        print_tree(tree)
     
    if __name__ == '__main__':
        test()

    输出

    ROOT/
     +- etc/
     |   +- passwd
     |   +- init.d/
     |   |   +- apache2
     |   |   +- sshd
     |   |   +- slapd
     |   +- hosts
     +- bin/
     |   +- cp
     |   +- bash
     |   +- cat
     +- var/
         +- log/
             +- apache2/
                 +- errorlog
                 +- accesslog
  • 相关阅读:
    Linux与Mac通信
    练习
    删除重复文件
    解压压缩文件
    查询压缩文件的大小
    修改文件夹和文件名字
    删除文件和文件夹
    移动文件和文件夹
    shutil复制文件夹
    shutil复制文件
  • 原文地址:https://www.cnblogs.com/colipso/p/4330979.html
Copyright © 2020-2023  润新知