Pathlib Tree Query And grouping

Query directory trees with pathlib glob and rglob, resolve sizes and suffixes, and bucket files by type without os.path string surgery.

PythonData Fetching

Code

pythonsnippet
27 lines
from pathlib import Path
from collections import defaultdict


def summarize(root: Path) -> dict:
    by_suffix = defaultdict(lambda: [0, 0])
    for path in root.rglob('*'):
        if not path.is_file():
            continue
        stat = path.stat()
        bucket = by_suffix[path.suffix.lower() or '(none)']
        bucket[0] += 1
        bucket[1] += stat.st_size
    return dict(by_suffix)


if __name__ == '__main__':
    root = Path(__file__).resolve().parent  # 脚本所在目录做演示
    # rglob 惰性遍历;suffix 属性替代字符串切分
    demo = root / 'tree-demo'
    demo.mkdir(exist_ok=True)
    (demo / 'a.txt').write_text('hello', encoding='utf-8')
    (demo / 'nested').mkdir(exist_ok=True)
    (demo / 'nested' / 'b.md').write_text('# hi', encoding='utf-8')

    for suffix, (count, total) in sorted(summarize(demo).items()):
        print(f'{suffix:<8} {count} files {total} bytes')

Output

Captured from a sandboxed run of this snippet in the build pipeline.

.md      1 files 4 bytes
.txt     1 files 5 bytes

How it works

Pathlib Tree Query And grouping is built around the function summarize.

Repetition is confined to for path in root.rglob('*') — the rest of the file is straight-line.

Putting it to use

Entry signature: def summarize(root: Path) -> dict

Interactive Tools for This Topic

FAQ

How do you run Pathlib Tree Query And grouping?
Nothing to install first — run the file and the program does the rest.