os.walk() 可以用于字符串列表吗?如果不是,那么等价物是什么? [英] Can os.walk() be used on a list of strings? If not, what would be the equivalent?

查看:35
本文介绍了os.walk() 可以用于字符串列表吗?如果不是,那么等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以给它一个预制的字符串列表,而不是使用真正的文件结构,让它为您创建一个嵌套的路径/文件列表?

Instead of using a real file structure, is it possible to give it a premade list of strings to have it create a nested list of paths/files for you?

示例列表(格式化以便可读):

Example List (formatted so it's readable):

files = [
    'user/hey.jpg',
    'user/folder1/1.txt',
    'user/folder1/folder2/random.txt',
    'user/folder1/blah.txt',
    'user/folder3/folder4/folder5/1.txt',
    'user/folder3/folder4/folder5/3.txt',
    'user/folder3/folder4/folder5/2.txt',
    'user/1.jpg'
    ]

这是我希望的输出:

['user'['1.jpg','hey.jpg','folder1'['1.txt','blah.txt','folder2'['random.txt']],'folder3'['folder4'['folder5'['1.txt','2.txt','3.txt']]]]]

我在这里问了一个类似的问题:如何根据 Python 中匹配的文件夹路径将文件路径字符串嵌套到列表中

I asked a similar question here: How would I nest file path strings into a list based upon matching folder paths in Python

我收到一条评论说 os.walk() 是我想要的理想选择,但无论我看哪里,似乎人们都在使用它来抓取文件系统,而不是通过它是已创建文件路径的列表.

I got a comment saying os.walk() would be ideal for what I wanted, but everywhere I look, it seems that people are using it to crawl the file system, as opposed to passing it a list of already created file paths.

推荐答案

只需创建一棵树.显示示例的快速草稿:

Just create a tree. Quick draft to show an example:

import pprint

files = [
    'user/hey.jpg',
    'user/folder1/1.txt',
    'user/folder1/folder2/random.txt',
    'user/folder1/blah.txt',
    'user/folder3/folder4/folder5/1.txt',
    'user/folder3/folder4/folder5/3.txt',
    'user/folder3/folder4/folder5/2.txt',
    'user/1.jpg'
    ]

def append_to_tree(node, c):
    if not c:
        return

    if c[0] not in node:
        node[c[0]] = {}

    append_to_tree(node[c[0]], c[1:])

root = {}
for path in files:
    append_to_tree(root, path.split('/'))

pprint.pprint(root)

输出:

{'user': {'1.jpg': {},
          'folder1': {'1.txt': {},
                      'blah.txt': {},
                      'folder2': {'random.txt': {}}},
          'folder3': {'folder4': {'folder5': {'1.txt': {},
                                              '2.txt': {},
                                              '3.txt': {}}}},
          'hey.jpg': {}}}

如果可以使用字典而不是列表,那么无论如何都可以轻松更改.

If it's all right to have dicts instead of lists, easy to change anyway.

这篇关于os.walk() 可以用于字符串列表吗?如果不是,那么等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆