不是使用真正的文件结构,而是可以为它提供一个预先制作的字符串列表,让它为你创建一个嵌套的路径/文件列表?
示例列表(格式化,使其可读):
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']]]]]
我在这里问了一个类似的问题:How would I nest file path strings into a list based upon matching folder paths in Python
我得到一条评论说os.walk()
对我想要的东西来说是理想的,但在我看来,似乎人们正在使用它来抓取文件系统,而不是传递已经创建的文件列表路径。
答案 0 :(得分:1)
只需创建一棵树。快速草案显示一个例子:
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': {}}}
如果可以使用dicts代替列表,那么无论如何都很容易改变。