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:
Python
>>> 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:
Python
>>> import glob
>>> glob.glob("*.txt")
['file1.txt', 'file2.txt', 'test.txt']
Find all text files in the directory and its subdirectories:
Python
>>> 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:
Python
>>> 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.