M
M
Matweytt2019-09-20 12:28:30
Python
Matweytt, 2019-09-20 12:28:30

How to make a directory tree from an array of paths?

There is an array of type string mas = [
E:/folder/maps
E:/1/2/3
E:/folder/new
E:/folder/maps/2
D:/papka/echepapka
E:/1/path/dir
]
What algorithm to bypass this array to get the hierarchy of all folders?
Preferably in python

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Dugin, 2019-09-20
@Matweytt

For example, you can add to a dictionary:

from functools import reduce
from pathlib import PurePosixPath

paths = [
    'E:/folder/maps',
    'E:/1/2/3',
    'E:/folder/new',
    'E:/folder/maps/2',
    'D:/papka/echepapka',
    'E:/1/path/dir',
]

tree = {}
for path in map(PurePosixPath, paths):
    reduce(lambda node, part: node.setdefault(part, {}), path.parts, tree)

Result:
{'E:': {'folder': {'maps': {'2': {}}, 'new': {}},
  '1': {'2': {'3': {}}, 'path': {'dir': {}}}},
 'D:': {'papka': {'echepapka': {}}}}

S
sim3x, 2019-09-20
@sim3x

https://docs.python.org/3/library/os.html#os.walk

T
tsarevfs, 2019-09-20
@tsarevfs

Yes, it seems that a cunning algorithm is not needed here. Take the next line, break it into separate tokens.
Further in the token loop, you try to find a partial path, and if it doesn’t work, add it to the tree.
For example, you added the first 2 paths:

E
|-1
| |-2
|   |-3
|-folder
  |-maps

Add "E:/folder/new" This is a set of tokens ["E:", "folder", "new"]. E: is in our tree, go to this subtree.
folder is there again. new is not found, add it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question