convert file path list to tree
Asked Answered
O

1

-2

There is a python file path list like below:

file_path_list = ["test/dir1/log.txt", "test/dir1/dir2/server.txt", "test/manage/img.txt"]

I want to convert it to a tree. the expect result is below:

 tree_data = [
    {
      "path": "test",
      "children": [
        {
          "path": "dir1",
          "children": [
            {
              "path": "log.txt"
            },
            {
              "path": "dir2",
              "children": [
                {
                  "path": "server.txt"
                }
              ]
            }
          ]
        },
        {
          "path": "manage",
          "children": [
            {
              "path": "img.txt",
            }
          ]
        }
      ]
    }
  ]

What's the best way to convert?

update: my code is below, but I think it's not well.

    def list2tree(file_path):
        """Convert list to tree."""
        tree_data = [{
            "path": "root",
            "children": []
        }]
        for f in file_path:
            node_path = tree_data[0]
            pathes = f.split("/")
            for i, p in enumerate(pathes):
                length = len(node_path["children"])
                if not length or node_path["children"][length - 1]["path"] != p:
                    # create new node
                    new_node = {
                        "path": p,
                    }
                    if i != len(pathes) - 1:  # middle path
                        new_node["children"] = list()
                    node_path["children"].append(new_node)
                    node_path = new_node
                else:
                    node_path = node_path["children"][length - 1]
        return tree_data

I think this way is not the best. any ideas? Thank you very much!

Offcolor answered 15/8, 2017 at 5:56 Comment(1)
Forget about the best way. Did you try anything at all, best or not?Pacifistic
R
0

One way is to split the strings at '/' and put them in a defaultdict of defaultdicts, see defaultdict of defaultdict, nested.

Roshan answered 15/8, 2017 at 6:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.