Can Os.walk() Be Used On A List Of Strings? If Not, What Would Be The Equivalent?
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
Solution 1:
Just create a tree. Quick draft to show an example:
importpprintfiles= [
'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:
returnif 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.
Post a Comment for "Can Os.walk() Be Used On A List Of Strings? If Not, What Would Be The Equivalent?"