How to use glob() to find files recursively?

You can use the glob.glob() function from the glob module to search for files recursively. The glob() function takes a pattern and returns a list of matching file names. You can use the ** wildcard to search for files recursively. For example:

import glob

files = glob.glob('**/*.txt', recursive=True)
print(files)

This will search for all .txt files in the current directory and all subdirectories, and return a list of the file names.

Watch a course Python - The Practical Guide

You can also use the os.walk() function to search for files recursively. os.walk() returns a tuple containing the directory name, a list of subdirectories, and a list of file names in each directory. You can use this to search for files recursively by iterating over the tuple and checking each file name.

import os

for root, dirs, files in os.walk('.'):
    for name in files:
        if name.endswith('.txt'):
            print(os.path.join(root, name))

This will search for all .txt files in the current directory and all subdirectories, and print the full path of each file.