Count the number of files in subdirectories in Python

Python

Assume the you have the following directory tree:

directory
  - subdirectoryA
    - image1.png
    - image2.png
    - ...
  - subdirectoryB
    - image1.png
    - image2.png
  - ...

You can count the number of files in each directory and print out the result.

Using os

import os

path = 'path/to/directory'

total = 0
for sub_dir in os.listdir(path):
    target_dir = path + '/' + sub_dir
    files = os.listdir(target_dir)
    count = len(files)
    total += count
    print(f'{sub_dir}: {count}')
print(f'Total: {total}')

The result will look like this:

subdirectoryA: 100
subdirectoryB: 120
...
Total: 1000

Using pathlib

from pathlib import Path

data_root = Path('path/to/directory')

total = 0
for sub_dir in data_root.iterdir():
    count = len(list(sub_dir.iterdir()))
    total += count
    print(f'{sub_dir.name}: {count}')
print(f'Total: {total}')

Comments

Copied title and URL