python目录和文件列表 - 树结构输出

时间:2014-01-14 14:41:04

标签: python python-2.7 tree ascii

是否可以使用Python(或某种类型的lib)生成目录及其所有子目录+文件的基于ascii的树结构?

我尝试过很多东西,但不幸的是我无法解决这个问题。

输出的一个例子看起来像这样

[rootdir]
|
+--- [subdir0]
|
+--- [subdir1]
|     |
|     +--- file1
|     +--- file2
|
+--- [subdir2]
|     |
|     +--- [subdir3]
|     |
|     +--- [subdir4]
|           |
|           +--- [subdir5]
|                 |
|                 +--- [subdir6]
|                 |     |
|                 |     +--- file4
|                 |
|                 +--- file3
+--- file5
+--- file6

编辑:

请求我当前(令人遗憾的)脚本。

def treeStructure(startpath):

    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 2 * (level)
        print('{}|'.format(indent[:]))
        print('{}+{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 2 * (level + 1)

        for f in files:
            print('{}| +--- {}'.format(subindent[:-2], f))

2 个答案:

答案 0 :(得分:4)

Linux上有一个名为tree的实用程序已经执行此操作。

您还可以签出此Python snippet以生成ASCII树。

答案 1 :(得分:0)

我知道是

  

糟糕的编程

代码,但是可以。 ;)

您在这里:

import os

# start point
startpath = '.'

folders = []    # folder store
tuples = []     # folders, subdirs, files


def folder_tree(line, dir):
    one = '|-> V '
    padding = '|   '

    if line == dir:
        # print('V '+line)
        return ('V '+line)

    if line.count(os.sep) == 1:
        line = line.split(os.sep)
        line[0] = one
        # print(''.join(line))
        return (''.join(line))

    if line.count(os.sep) >= 2:
        line = line.split(os.sep)
        line[-2] = one
        for i in range(len(line[:-2])):
            line[i] = padding
        # print(''.join(line))
        return (''.join(line))


def files_tree(dir, *args):
    """

    :param dir: startpath
    :param args: args[0] > tuples, args[1] > folders
    :return: None
    """
    file = '|-> '
    padding = '|   '
    last_file = ''
    tuples = args[0]
    folders_list = args[1]
    for root, subs, files in tuples:
        # no files no worries, skip
        if not files:
            continue

        # will use for padding: padding * sep
        sep = root.count(os.sep)

        # only if root has some files
        if root == dir:
            last_file = [file+str(x) for x in files]
            continue

        if subs:
            # take last elem in subs,
            # use it as value to find the same in folders_list
            # get index + 1 to insert right after
            index = folders_list.index([x for x in folders_list if x.endswith(subs[-1])][0]) + 1

        else:
            # we need name the last of folder in the root
            # to use it to find index
            folder_name = root.split(os.sep)[-1]
            index = folders_list.index([x for x in folders_list if x.endswith(folder_name)][0]) + 1

        # prepare files
        files = [sep * padding + file + x for x in files]

        # now insert files to list
        for i, a in enumerate(range(index, index+len(files))):
            folders_list.insert(a, files[i])

    if last_file:
        # merge files in root dir
        folders_list = folders_list + last_file

    # final print tree
    for elm in folders_list:
        print(elm)


def tree_walk(dir):
    for folder, subs, files in os.walk(dir):
        tuples.append((folder, subs, files))
        folders.append(folder_tree(folder, dir))


tree_walk(startpath)
folder_tree(tuples, startpath)
files_tree(startpath, tuples, folders)

这是结果:

V .
|-> V folder1
|   |-> V folder2
|   |   |-> V folder3
|   |   |   |-> file3.txt
|   |   |-> file2.txt
|   |-> V folderX
|   |-> file1.txt
|-> 02-hw1_wdwwfm.py
|-> 06-t1-home1.py
|-> 06-t1-home2.py
|-> hw1.py