liveBook · Manning

Path.glob

As explained in The Quick Python Book, Fourth Edition

Path.glob is a pathlib method that yields path objects matching a filesystem pathname pattern relative to a path.

Path.glob(pattern) searches relative to a Path and yields matching path objects rather than strings. Convert the iterator to a list when you need to inspect all matches. section 12.4.1

Find matching files

from pathlib import Path cur_path = Path("sample_data") list(cur_path.glob("*json")) # [PosixPath('sample_data/anscombe.json')] list(cur_path.glob("?.tmp")) # [PosixPath('sample_data/1.tmp'), PosixPath('sample_data/2.tmp')]

Use matches in a filesystem task

from pathlib import Path size = 0 for file in Path().rglob("*.test"): if not file.is_symlink(): size += file.stat().st_size print(size)

list(cur_path.glob("*"))
 
[PosixPath('anscombe.json'),
 PosixPath('.ipynb_checkpoints'),
 PosixPath('README.md.old'),
 PosixPath('1.tmp'),
 PosixPath('2.tmp'),
 PosixPath('california_housing_train.csv'),
 PosixPath('california_housing_test.csv'),
 PosixPath('mnist_test.csv'),
 PosixPath('mnist_train_small.csv')]
 
list(cur_path.glob("*json"))
 
[PosixPath('anscombe.json')]
 
list(cur_path.glob("?.tmp"))
 
[PosixPath('1.tmp'), PosixPath('2.tmp')]
 
list(cur_path.glob("[0-9].tmp"))
 
[PosixPath('1.tmp'), PosixPath('2.tmp')]

Compare wildcard, suffix, single-character, and character-class patterns with their resulting Path objects. section 12.4.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines iterator behavior and demonstrates wildcard, suffix, single-character, and character-class patterns without descending into implementation internals.
Examples
Demonstrates directory listings, JSON and temporary-file patterns, and selecting non-symlink .test files for size calculation.
What it assumes
Assumes general Python knowledge and teaches the pathlib alternative to string-based os filesystem operations.
What you can do after
Apply it via pathlib to select matching paths and combine them with filesystem checks and metadata operations.
How it connects
Connects pathlib Path objects with glob.glob, rglob, is_symlink, stat, and rename for filesystem workflows.

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.