Python Glob Module File Matching Guide | Generated by AI

Home 2025.10

Importing Glob

To use glob in Python, import the module from the standard library:

import glob

Basic Functionality

The glob.glob() function takes a pattern string and returns a list of matching file or directory paths. It uses Unix shell-style wildcards:

Patterns are relative to the current directory unless an absolute path is specified.

Usage Examples

1. Find all .txt files in the current directory

import glob

files = glob.glob("*.txt")
print(files)  # Output: ['file1.txt', 'file2.txt', ...]

2. Find files with specific extensions in a subdirectory

files = glob.glob("documents/*.pdf")
print(files)  # Output: ['documents/doc1.pdf', ...]

3. Match specific patterns (e.g., files starting with ‘log’ and ending with numbers)

files = glob.glob("log[0-9].txt")
print(files)  # Output: ['log1.txt', 'log2.txt', ...] if such files exist

4. Recursive search in subdirectories

Use ** with recursive=True to search directories and subdirectories:

files = glob.glob("**/*.py", recursive=True)
print(files)  # Output: ['script1.py', 'subdir/script2.py', ...]

Important Notes

This covers the essentials; refer to the Python documentation for more details.


Back

x-ai/grok-code-fast-1

Donate