glob2
glob2 is an extended version of Python's built-in `glob` module, designed to offer enhanced globbing capabilities. Key features include the ability to capture patterns matched by glob expressions and a recursive `**` wildcard syntax, akin to bash's globstar. The current version is 0.7. The project has seen no active development since 2019, as many of its core functionalities, particularly recursive globbing, have been integrated into Python's standard `glob` module since Python 3.5.
Warnings
- deprecated The primary features of `glob2`, specifically recursive globbing with `**`, have been integrated into Python's standard `glob` module since Python 3.5. `pathlib` also provides robust globbing functionality. There is generally no compelling reason to use `glob2` in modern Python versions.
- breaking The `glob2` library is no longer actively maintained. The last release was in 2019, and the last code push was over 4 years ago. This means it may not be compatible with newer Python versions or address new security vulnerabilities or bugs.
- gotcha The recursive wildcard `**` in `glob2` (and standard `glob`) must appear as a standalone directory element. For example, `src/**/*.h` is correct, but `src/**h` will not have the desired recursive effect. Additionally, `**/*.py` will match Python files in the current directory (`.`), if not intended, use `*/**/*.py` to exclude the current directory.
- gotcha When using Windows file paths, backslashes are interpreted as escape characters. This can lead to incorrect path matching or errors.
Install
-
pip install glob2
Imports
- glob2
import glob2
Quickstart
import glob2
import os
# Create some dummy files and directories for demonstration
os.makedirs('src/media/mp3', exist_ok=True)
with open('src/fs.h', 'w') as f: f.write('// fs.h')
with open('src/media/mp3.h', 'w') as f: f.write('// mp3.h')
with open('src/media/mp3/frame.h', 'w') as f: f.write('// frame.h')
with open('src/main.py', 'w') as f: f.write('# main.py')
# Example 1: Recursive globbing with '**'
print('All header files:')
all_header_files = glob2.glob('src/**/*.h')
for f in all_header_files:
print(f)
# Example 2: Capturing patterns (with_matches=True)
# This example requires a pattern that defines capture groups, e.g., project-(.*).zip
# For demonstration, let's assume we have files like 'binaries/project-v1.0.zip'
os.makedirs('binaries', exist_ok=True)
with open('binaries/project-v1.0.zip', 'w') as f: f.write('zip content')
with open('binaries/project-v2.1.zip', 'w') as f: f.write('zip content')
print('\nProject versions (captured patterns):')
for filename, (version,) in glob2.iglob('./binaries/project-*.zip', with_matches=True):
print(f'{filename}, version: {version}')
# Clean up dummy files and directories
import shutil
shutil.rmtree('src', ignore_errors=True)
shutil.rmtree('binaries', ignore_errors=True)