1 min read

Python Glob Module

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order.

Importing the Module

import glob

Basic Usage

The glob.glob() function returns a list of files that match the pattern.

import glob

# Find all .py files in the current directory
files = glob.glob('*.py')
print(files)

Wildcards

  • *: Matches zero or more characters.
  • ?: Matches exactly one character.
  • []: Matches a range of characters.
import glob

# Find files starting with 'file' and ending with .txt
print(glob.glob('file*.txt'))

# Find files with a single character name
print(glob.glob('?.txt'))

# Find files with a number range
print(glob.glob('[0-9].txt'))

If recursive is true, the pattern ** will match any files and zero or more directories, subdirectories and symbolic links to directories.

import glob

# Find all .txt files in current directory and subdirectories
files = glob.glob('**/*.txt', recursive=True)
print(files)

Iterators

glob.iglob() returns an iterator which yields the same values as glob() without actually storing them all simultaneously.

import glob

for file in glob.iglob('**/*.py', recursive=True):
    print(file)

programming/python/python