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.
Code
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 bytesHow 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
GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.
FAQ
- How do you run Pathlib Tree Query And grouping?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.