liveBook · Manning

Glob module

As explained in Python Workout, Second Edition

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

Use glob when a directory contains many files but your program should process only names matching a shell-style pattern. Unlike os.listdir, glob.glob returns matching pathnames with their directory prefixes, avoiding separate path construction. section 6.17

A practical glob workflow is:

  • Choose a directory and pattern, such as *.conf or *.json. section 6.17 section 6.23
  • Call glob.glob(pattern) and iterate over the returned filename strings. section 6.23
  • Open or otherwise process each selected file without manually adding the directory name. section 6.17

Collect JSON score files

import glob for filename in glob.glob('scores/*.json'): process(filename) section 6.23

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

Compare the compact glob.glob call with os.listdir, then consider pathlib.Path.glob when Path objects are more useful than strings. section 6.17

How Python Workout, Second Edition covers it

How deep it goes
Explains glob.glob usage and contrasts it with os.listdir and pathlib, without detailing wildcard semantics beyond * and ?.
Examples
Uses /etc/*.conf for configuration files and scores/*.json for selecting class score files.
What it assumes
Assumes familiarity with directories, filenames, file paths, and iterating over lists.
What you can do after
Apply it via glob.glob to gather matching pathnames for subsequent file processing.
How it connects
Connects glob with os.listdir, pathlib, Path objects, and JSON file processing.

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, Second Edition. The section links point to the parts of the book it draws on.