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
