Python 3.4+pathlibfunction
.glob()
search
Match files against a pattern inside the directory, yielding paths lazily; the `**/` pattern walks recursively.
Syntax
p.glob('*.py')
You get a lazy iterator (a map object in 3.14), not a list: len() does not work on it and you cannot iterate it twice — wrap it in list() if you need the results more than once. The order comes from the filesystem and is not sorted, so use sorted() when output must be reproducible. Each pattern component is matched against one path segment, and a '**' pattern over a large tree can take a very long time.
Examples
from pathlib import Path
root = Path('glob_demo')
(root / 'pkg').mkdir(parents=True, exist_ok=True)
for name in ('a.txt', 'b.txt', 'main.py', 'pkg/util.py'):
(root / name).touch()
print(sorted(p.name for p in root.glob('*.txt'))) # → ['a.txt', 'b.txt']
print([p.name for p in root.glob('*/*.py')]) # → ['util.py'] — на уровень глубже
print(sorted(p.name for p in root.glob('**/*.py'))) # → ['main.py', 'util.py'] — рекурсивно
See also
Open in the full glossarydocs.python.orgReport an inaccuracy