Codiqo

Learn Python · lesson 52 of 60 · about 10 minutes

Project: Nested Folders

Use recursion to add up the sizes of files hidden inside folders inside folders.

What you'll learn

  • Recognise nested data that recursion suits
  • Check what kind of item you have with isinstance
  • Total a folder tree of any depth

Sam's drive

Sam's files live in folders inside folders: photos/trip/beach.png is beach.png, inside trip, inside photos. The assistant reads each file as a path and a size, like photos/trip/beach.png 500, and puts it in a dictionary of folders, making any folder that isn't there yet. Then recursion takes over: it adds up the sizes, counts the files and shows the whole drive with every folder's contents indented under it, however deep they go.

Folders inside folders

A folder can hold files and other folders, which can hold more folders, as deep as you like. A loop can't know how many levels to go down, but recursion can.

We'll store a folder as a dictionary: each key is a name, and each value is either a file size (an int) or another folder (a dict).

What kind of item is it?

photos = {"cat.png": 300, "trip": {"beach.png": 500}}
for name, item in photos.items():
    print(name, isinstance(item, dict))

Output

cat.png False
trip True

The recursive total

For each item in a folder: a file adds its size, and a folder adds its own total, worked out by the same function. A folder with nothing in it totals 0, so there's no special base case: the loop simply finds no more folders to go into.

Total size

def size(folder):
    total = 0
    for item in folder.values():
        if isinstance(item, dict):
            total += size(item)
        else:
            total += item
    return total

drive = {"notes.txt": 20, "photos": {"cat.png": 300, "trip": {"beach.png": 500}}}
print(size(drive))
print(size({}))

Output

820
0

Showing the tree

To print the drive, pass a second parameter, depth, and give every line " " * depth in front. A file prints its name and size; a folder prints its name with a /, then calls the same function on itself with depth + 1, so its contents come out one step further in.

Indented by depth

def show_tree(folder, depth):
    for name, item in folder.items():
        if isinstance(item, dict):
            print("  " * depth + name + "/")
            show_tree(item, depth + 1)
        else:
            print("  " * depth + name)

show_tree({"notes.txt": 20, "photos": {"cat.png": 300, "trip": {"beach.png": 500}}}, 0)

Output

notes.txt
photos/
  cat.png
  trip/
    beach.png

Tip

isinstance(item, dict) asks "is this a dictionary?". It's the usual way to choose between going deeper and treating the item as a plain value.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.