Python: Trees
2026-02-21 02:54 Diff

Full access to materials

Sign up and get access to this and dozens of other courses

Sign up

Let's practice with another option for data aggregation on file systems. We'll write a function that accepts a directory as input and returns a list of directories of the first level of nesting and the number of files inside each of them, including all subdirectories:

We can break this task down into two steps:

  • Counting the number of files inside a directory
  • Calling the file counting function on each of the subdirectories

Let's start by counting the number of files. It is a classic aggregation task:

The next step is to extract all the children from the source node and apply a count to each of them:

In other words, we addressed the children directly, filtered them, and then mapped them to the necessary array containing names and numbers of files for each directory.