glob
The Python glob
module provides tools to find path names matching specified patterns that follow Unix shell rules. You can use this module for file and directory pattern matching.
Here’s a quick example that looks for all the .py
files in the current directory:
>>> import glob
>>> glob.glob("*.py")
['script.py', 'module.py', 'test_script.py']
Key Features
- Performs pattern matching to find files and directories
- Supports Unix shell-style wildcards (
*
,?
,[]
) - Can search recursively
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
glob.glob() |
Function | Returns a list of paths matching a path pattern |
glob.iglob() |
Function | Returns an iterator that yields the paths matching |
glob.escape() |
Function | Escapes special characters in a path name |
glob.translate() |
Function | Converts the given path specification to a regular expression |
Examples
Find all text files in the current directory:
>>> import glob
>>> glob.glob("*.txt")
['file1.txt', 'file2.txt', 'test.txt']
Find all text files in the directory and its subdirectories:
>>> glob.glob("**/*.txt", recursive=True)
['notes.txt', 'docs/info.txt', 'archive/old_notes.txt']
Common Use Cases
- Listing all files of a certain type in a directory
- Searching for files with specific naming patterns
- Recursively finding files in a directory tree
Real-World Example
Suppose you want to find all image files (with extensions .jpg
, .png
, .gif
) in a directory and its subdirectories:
>>> import glob
>>> image_files = glob.glob('**/*.jpg', recursive=True) + \
... glob.glob('**/*.png', recursive=True) + \
... glob.glob('**/*.gif', recursive=True)
...
>>> image_files
['images/photo.jpg', 'graphics/logo.png', 'pictures/image.gif']
This snippet demonstrates how to use the glob
module to locate image files in a directory tree by using pattern matching.
Related Resources
Tutorial
How to Get a List of All Files in a Directory With Python
In this tutorial, you'll be examining a couple of methods to get a list of files and folders in a directory with Python. You'll also use both methods to recursively list directory contents. Finally, you'll examine a situation that pits one method against the other.
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated July 9, 2025