Another useful module for pattern matching is glob module. The glob( ) method in the glob module works just like fnmatch.fnmatch(), but unlike fnmatch.fnmatch( ), it treats files beginning with a period (.) as special.

 

UNIX and related systems translate name patterns with wildcards like ? and * into a list of files. This is called globbing. For example, typing “mv *.py python_files/ ” in a UNIX shell will move (mv) all files with the .py extension from the current directory to the directory python_files. The * character is a wildcard that means “any number of characters,” and *.py is the glob pattern. This shell capability is not available in the Windows Operating System. The glob module adds this capability in Python, which enables Windows programs to use this feature.

 

pathlib contains similar methods for making flexible file listings. The example below shows how you can use Path.glob() to list file types that start with the letter b:

 

from pathlib import Path
p = Path('.')
for name in p.glob('*.b*'):
    print(name)