The glob
module provides a way to search for files and directories using pattern matching rules similar to those used in the command-line shell. It allows us to find files based on their names or specific patterns.
Here's an example of how you can use the glob
module:
import glob # Find all python files in the current directory py_files = glob.glob("*.py") print(py_files)
In this code, we import the glob
module and use the glob.glob()
function to search for files based on patterns. We can then search for all python files (*.py
) in the current directory. The glob.glob()
function returns a list of matching file names, which we print.
As a second example, let's search for all Python files (*.py
) in a specific directory ("/home") and its subdirectories.
# Find all Python files in a specific directory and its subdirectories py_files = glob.glob("/home/**/*.py", recursive=True) print(py_files)
By using the **
pattern and setting recursive=True
, the glob.glob()
function searches for files recursively in all subdirectories.
The glob
module supports various pattern matching rules, including wildcards (*
and ?
), character ranges ([...]
), and recursive matching (**
). It provides a flexible and convenient way to search for files and directories based on specific patterns.