Brick_Porter 发表于 2021-8-1 17:20:01

树形打印目录结构

CMD中没有tree这个命令,所以自己使用Python编写了一个可以遍历目录而且还是以树形图表的形式显示目录结构的脚本,
代码如下:'''If a directory is like this:
root/
|-- dir1/
|   |-- file1.txt
|   |-- file2.txt
|   |-- sub1/
|   |   |-- video1.mp4
|   |   |-- video2.mp4
|   |   |-- video3.mp4
|   |   `-- sub_n/
|   |       |-- f1.png
|   |       `-- f2.png
|   `-- sub2/
|       |-- pic1.jpg
|       |-- pic2.jpg
|       `-- pic3.jpg
|-- dir2/
|   |-- text1.md
|   |-- text2.md
|   `-- text3.md
|-- main.py
|-- spam.py
|-- eggs.py
`-- hams.py

Each row has three components: prefix, item and suffix.
Definitions are as follow:

prefix:
    A prefix is everything before a file or a directory and it
    also has three parts: upper prefix, indent and item mark.
    * A upper prefix is a prefix before a directory, which will be
      used to create new prefix for items within a directory.
      Root directory's prefix is an empty string.
    * Indent is either '|   ' or '    '.
    * Item mark is adjacent to a file or a directory,
      which is '`-- ' for last item or '|-- ' for everything except
      the last one in a direcotry.

item:
    An item is either a directory or a file.

suffix:
    Only a directory has a suffix '/'.
'''

from os import listdir
from os.path import abspath, basename, isdir, join

MARK_1 = '    '# indentation
MARK_2 = '|   '# indentation
MARK_3 = '|-- '# mark adjacent to a file or a directory
MARK_4 = '`-- '# mark for the last item of a directory


def tree(dir_: str, prefix: str = '', indent: str = '') -> None:
    '''Iter recursively a directory to print everything within it in
    an ascii tree graph.

    :param dir_: str, a root directory.
    :param prefix: str, everything before a file or a directory.
    :param indent: str, indent mark for building new prefix.
    '''

    # print directory
    print(f'{prefix}{basename(abspath(dir_))}/')

    # |--
    prefix = prefix[:-len(MARK_3)] + indent + MARK_3

    contents = listdir(dir_)
    max_indx = len(contents) - 1
    for idx, item in enumerate(contents):
      path = join(dir_, item)
      if isdir(path):
            if idx < max_indx:
                tree(path, prefix, MARK_2)
            else:
                tree(path, prefix.replace(MARK_3, MARK_4), MARK_1)
      else:
            if idx == max_indx:
                prefix = prefix.replace(MARK_3, MARK_4)
            # print file
            print(f'{prefix}{item}')


if __name__ == '__main__':
    tree('.')

使用的是递归,话说递归确实有点难啊
其他同学也可以试试用argparse这个标准库把代码改装成一个命令行工具
页: [1]
查看完整版本: 树形打印目录结构