📂 glob Module

Last Updated: 25th August 2025


The glob module allows you to use wildcards to match multiple file names in a directory. It is useful for searching for files with specific patterns.

List of Glob Functions:

glob.glob(pattern): Returns a list of paths that match the specified pattern.

1 *.txt: Matches any file with the extension .txt.

import glob
pattern = "*.txt"
matching_files = glob.glob(pattern)
print("Matching files:", matching_files)

2. */: Matches any directory.

pattern = "*/"
matching_directories = glob.glob(pattern)
print("Matching directories:", matching_directories)

3. directory + "/*.txt": Matches any file with the extension .txt in the specified directory.

directory = "/path/to/directory"z
pattern = directory + "/*.txt"
matching_files = glob.glob(pattern)
print("Matching files in", directory, ":", matching_files)

4. '*.py', recursive=True.: Returns a list of file paths matching *.py in the current directory and all subdirectories, using recursive search.

print(glob.glob('*.py', recursive=True))

5. ?.extension: Returns a list of file paths matching the pattern ?.extension, where ? is a wildcard that matches any single character (except directory separators).

#e.g. data?.txt, data?.csv etc. This finds files like data1.csv, dataX.csv, etc.

print(glob.glob('data?.csv'))

glob.iglob(pattern): Returns an iterator that yields paths that match the specified pattern.

import glob
for py_file in glob.iglob("*.py"):
    print("Found Python file:", py_file)