liveBook · Manning

Glob module

As explained in The Quick Python Book, Fourth Edition

The glob module is a Python standard-library module that finds filesystem pathnames matching shell-style wildcard patterns.

The glob module finds filesystem pathnames that match shell-style wildcard patterns. Its glob function returns matching files from the current working directory, making it useful when filenames follow a predictable pattern but are not known exactly. section 12.4

Use these pattern forms to control which pathnames match:

Match files in the current directory

import glob glob.glob("*") # all matching names glob.glob("*json") # names ending in json glob.glob("?.tmp") # one-character names before .tmp glob.glob("[0-9].tmp") # digit names before .tmp section 12.4

import glob
glob.glob("*")
 
['anscombe.json',
 'README.md',
 'california_housing_train.csv',
 'california_housing_test.csv',
 'mnist_test.csv',
 'mnist_train_small.csv']
 
glob.glob("*json")
 
['anscombe.json']
 
glob.glob("?.tmp")
 
['1.tmp', '2.tmp', 'a.tmp']
 
glob.glob("[0-9].tmp")
 
['1.tmp', '2.tmp']

Inspect the resulting pathname lists for broad, suffix-based, single-character, and character-range patterns. section 12.4

For larger file-wrangling tasks, pathlib also provides a path object's glob method. That alternative can yield Path objects and fit naturally with operations such as renaming matching files and moving them into an archive. section 20.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines three wildcard forms and demonstrates their outputs, but does not discuss more complex matching requirements.
Examples
Demonstrates *, *json, ?.tmp, and [0-9].tmp against sample directory contents.
What you can do after
Apply it via glob.glob to collect filesystem names matching reusable wildcard patterns.
How it connects
Connects pathname matching with current working directories, pathlib, and filesystem operations.

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