从路径文件列表中列出python目录树结构

wvyml7n5  于 2022-12-02  发布在  Python
关注(0)|答案(3)|浏览(122)

该问题旨在扩大已通过主题“List directory tree structure in python?“在stackoverflow上回答的问题的范围。
目标是形成一个字符串列表,直观地表示目录树,带有分支
但是,不是输入一个有效的目录路径(就像在已经回答的主题中那样),而是要求生成一个与输入相同的行为,即“path file list”。
当然,该函数需要递归以适应任何深度的文件。
范例
输入:

['main_folder\\file01.txt',
 'main_folder\\file02.txt',
 'main_folder\\folder_sub1\\file03.txt',
 'main_folder\\folder_sub1\\file04.txt',
 'main_folder\\folder_sub1\\file05.txt',
 'main_folder\\folder_sub1\\folder_sub1-1\\file06.txt',
 'main_folder\\folder_sub1\\folder_sub1-1\\file07.txt',
 'main_folder\\folder_sub1\\folder_sub1-1\\file08.txt',
 'main_folder\\folder_sub2\\file09.txt',
 'main_folder\\folder_sub2\\file10.txt',
 'main_folder\\folder_sub2\\file11.txt']

输出:

├── file01.txt
├── file02.txt
├── folder_sub1
│   ├── file03.txt
│   ├── file04.txt
│   ├── file05.txt
│   └── folder_sub1-1
│       ├── file06.txt
│       ├── file07.txt
│       └── file08.txt
└── folder_sub2
    ├── file09.txt
    ├── file10.txt
    └── file11.txt

将文件路径列表转换为表示目录结构的嵌套字典已在主题“Python convert path to dict“中得到解答。

{'main_folder': {'file01.txt': 'txt',
                 'file02.txt': 'txt',
                 'folder_sub1': {'file03.txt': 'txt',
                                 'file04.txt': 'txt',
                                 'file05.txt': 'txt',
                                 'folder_sub1-1': {'file06.txt': 'txt',
                                                   'file07.txt': 'txt',
                                                   'file08.txt': 'txt'}},
                 'folder_sub2': {'file09.txt': 'txt',
                                 'file10.txt': 'txt',
                                 'file11.txt': 'txt'}}}

但如何生成具有分支的优美布局一直是一个难题。

woobm2wo

woobm2wo1#

可能的解决方案:

paths = {
    'main_folder': {
        'file01.txt': 'txt',
        'file02.txt': 'txt',
        'folder_sub1': {
            'file03.txt': 'txt',
            'file04.txt': 'txt',
            'file05.txt': 'txt',
            'folder_sub1-1': {
                'file06.txt': 'txt',
                'file07.txt': 'txt',
                'file08.txt': 'txt'
            }
        },
        'folder_sub2': {
            'file09.txt': 'txt',
            'file10.txt': 'txt',
            'file11.txt': 'txt'
        }
    }
}

# prefix components:
space =  '    '
branch = '│   '
# pointers:
tee =    '├── '
last =   '└── '

def tree(paths: dict, prefix: str = ''):
    """A recursive generator, given a directory Path object
    will yield a visual tree structure line by line
    with each line prefixed by the same characters
    """
    # contents each get pointers that are ├── with a final └── :
    pointers = [tee] * (len(paths) - 1) + [last]
    for pointer, path in zip(pointers, paths):
        yield prefix + pointer + path
        if isinstance(paths[path], dict): # extend the prefix and recurse:
            extension = branch if pointer == tee else space
            # i.e. space because last, └── , above so no more |
            yield from tree(paths[path], prefix=prefix+extension)

for line in tree(paths):
    print(line)

参考:List directory tree structure in python?

jfgube3f

jfgube3f2#

对@rafaeldss的回答稍作修改

# prefix components:
space =  '    '
branch = '│   '
# pointers:
tee =    '├── '
last =   '└── '

def tree(paths: dict, prefix: str = '', first: bool = True):
    """A recursive generator, given a directory Path object
    will yield a visual tree structure line by line
    with each line prefixed by the same characters
    """
    # contents each get pointers that are ├── with a final └── :
    pointers = [tee] * (len(paths) - 1) + [last]
    for pointer, path in zip(pointers, paths):
        if first:
            yield prefix + path
        else:
            yield prefix + pointer + path
        if isinstance(paths[path], dict): # extend the prefix and recurse:
            if first:
                extension = ''
            else:
                extension = branch if pointer == tee else space
                # i.e. space because last, └── , above so no more │
            yield from tree(paths[path], prefix=prefix+extension, first=False)

for line in tree(paths):
    print(line)

diffs

o8x7eapl

o8x7eapl3#

bigtree是一个Python树实现,它集成了Python列表、字典和PandasDataFrame。
对于这个场景,我们可以使用3行代码,

path_list = [
    'main_folder\\file01.txt',
    'main_folder\\file02.txt',
    'main_folder\\folder_sub1\\file03.txt',
    'main_folder\\folder_sub1\\file04.txt',
    'main_folder\\folder_sub1\\file05.txt',
    'main_folder\\folder_sub1\\folder_sub1-1\\file06.txt',
    'main_folder\\folder_sub1\\folder_sub1-1\\file07.txt',
    'main_folder\\folder_sub1\\folder_sub1-1\\file08.txt',
    'main_folder\\folder_sub2\\file09.txt',
    'main_folder\\folder_sub2\\file10.txt',
    'main_folder\\folder_sub2\\file11.txt']

from bigtree import list_to_tree, print_tree
root = list_to_tree(path_list, sep="\\")
print_tree(root)

这将导致输出,

main_folder
├── file01.txt
├── file02.txt
├── folder_sub1
│   ├── file03.txt
│   ├── file04.txt
│   ├── file05.txt
│   └── folder_sub1-1
│       ├── file06.txt
│       ├── file07.txt
│       └── file08.txt
└── folder_sub2
    ├── file09.txt
    ├── file10.txt
    └── file11.txt

来源/免责声明:我是bigtree的创造者;)

相关问题