Generate the tree structure data of a directory in the format of element-plus tree component (implement in python)

About the element-plus (element-UI) tree component

As the official document says, it uses data like:

const data: Tree[] = [
  {
    label: 'Level one 1',
    children: [
      {
        label: 'Level two 1-1',
        children: [
          {
            label: 'Level three 1-1-1',
          },
        ],
      },
    ],
  },
  {
    label: 'Level one 2',
    children: [
      {
        label: 'Level two 2-1',
        children: [
          {
            label: 'Level three 2-1-1',
          },
        ],
      },
      {
        label: 'Level two 2-2',
        children: [
          {
            label: 'Level three 2-2-1',
          },
        ],
      },
    ],
  },
]

Now I want to use the tree component to show the structure of a file directory. The file name and directory name will be the label, and the hierarchies will be achieved through the children key.

The backend API that gives the tree data is written in python.

Generate the tree structure in python

import os


def get_tree(dir_path):
   nodes = []
   dirs = []
   files = []
   for entry in os.scandir(dir_path):
      if entry.is_dir():
         dirs.append(entry)
      else:
         files.append(entry)
   for d in dirs:
       nodes.append({
          'label': d.name,
          'children': get_tree(d.path)
       })
   for f in files:
      nodes.append({
         'label': f.name
      })
   return nodes

Now, get_tree returns the exact data structure that element-plus needs.

Posted on 2023-04-11