Standard Library

Python glob Module

Python File Pattern Matching

Python glob module finds files with recursive pattern matching.

Introduction to the glob Module

The glob module in Python is a powerful tool for file pattern matching and directory traversal. It allows you to easily search for files and directories that match a specific pattern, using wildcards and recursive searching. This makes it ideal for tasks that involve file manipulation and organization.

Basic Usage of glob

The glob module provides a function called glob() that returns a list of path names matching a specified pattern. The pattern may include simple shell-style wildcards:

  • * matches everything
  • ? matches any single character
  • [seq] matches any character in the sequence

Recursive Searching with glob

With the advent of Python 3.5, the glob module includes support for recursive file searching. By using the ** pattern, you can search through all directories and subdirectories. You must also set the recursive parameter to True:

Using glob with Absolute Paths

The glob module can also be used with absolute paths. This is useful when you need to search for files outside the current working directory:

Limitations and Considerations

While the glob module is quite powerful, it has some limitations:

  • It does not support regular expressions, only shell-style wildcards.
  • On Windows, it may behave differently due to the underlying file system.

Despite these limitations, the glob module is widely used and remains a staple for file pattern searching in Python scripts.