liveBook · Manning

Path.rglob

As explained in The Quick Python Book, Fourth Edition

Path.rglob is a pathlib method that recursively yields paths matching a glob pattern beneath a path.

Path.rglob(pattern) finds matching paths recursively beneath a pathlib.Path. Use it when a filesystem task must reach into subdirectories without writing a separate directory-walking loop. section 12.6.2 section 12.7

Total the size of matching files

For a directory called sample_data: from pathlib import Path size = 0 for path in Path('sample_data').rglob('*.test'): if not path.is_symlink(): size += path.stat().st_size print(size) The pattern selects .test paths throughout the directory tree. The symlink check is separate from the pattern; stat().st_size supplies each accepted path’s size. section 12.6.2

Two useful ways to structure the search:

  • Use rglob('*.test') to select the desired extension in the search itself. section 12.6.2
  • Use rglob('*') and then test path.suffix == '.test' when extension checking belongs with other conditions. section 12.6.2

A matching path remains a Path object: it can be checked with is_symlink(), measured with stat(), or moved with rename(). If a backup directory sits inside the searched tree, exclude it when appropriate so previously moved files are not processed again. section 12.6.2

import pathlib
cur_path = pathlib.Path("sample_data")
new_path = pathlib.Path("backup")
new_path.mkdir(exist_ok=True)                       #1
 
size = 0
for text_path in cur_path.rglob("*.test"):
    if not text_path.is_symlink():
        size += text_path.stat().st_size
        text_path.rename(new_path / text_path.name) #2
 
print(size)

See a complete search that totals eligible .test files and moves them to a separate backup directory. section 12.6.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates glob patterns in working loops and subsequent Path operations; does not explain matching internals.
Examples
Uses .test-file size totals and a backup-directory move, with both pattern-based and suffix-based filtering.
What it assumes
Assumes familiarity with Python loops and conditions while showing the pathlib form alongside os-based filesystem code.
What you can do after
Apply it via pathlib to search subdirectories, filter paths, total file sizes, and move selected files.
How it connects
Connects recursive search to pathlib.Path, os.walk, Path.suffix, Path.is_symlink, Path.stat, and Path.rename.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.