Can os.walk() be used on a list of strings? If not, what would be the equivalent?

試著忘記壹切 提交于 2020-01-06 19:54:37

问题


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'
    ]

Here is the output I'm hoping for:

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

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

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.


回答1:


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)

Output:

{'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.



来源:https://stackoverflow.com/questions/42031246/can-os-walk-be-used-on-a-list-of-strings-if-not-what-would-be-the-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!