liveBook · Manning

Glob module

As explained in Python Workout: 50 ten-minute exercises

glob is a Python standard-library module for finding filesystem pathnames that match shell-style wildcard patterns.

When a program must process selected files rather than every directory entry, glob finds pathnames matching shell-style patterns such as *.json or *.conf. section 5.27 section 5.20

Use glob when:

  • You need files with a particular suffix, such as JSON or configuration files. section 5.27 section 5.20
  • You want returned strings to include the directory path, avoiding separate path construction. section 5.20
  • You prefer a pattern-based alternative to listing everything with os.listdir. section 5.20

Collect JSON files

import glob for filename in glob.glob('scores/*.json'): print(filename) The pattern selects JSON files inside scores, and each iteration receives a matching filename string. Those files can then be opened and processed, such as by loading a JSON array with json.load. section 5.27

filenames = glob.glob('/etc/*.conf')

Compare the concise pattern-based call with os.listdir, which returns unfiltered directory entries without the directory name. section 5.20

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines wildcard matching and demonstrates iteration, but defers detailed pattern syntax and implementation internals.
Examples
Uses scores/*.json and /etc/*.conf to select matching files.
What it assumes
Assumes familiarity with directories, filenames, iteration, and basic file and JSON processing.
What you can do after
Apply it via Python's glob.glob function to iterate over files matching a pathname pattern.
How it connects
Contrasts os.listdir and connects file selection with pathlib and JSON loading.

Also explained in

Compare how 3 books explain glob module →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.