String methods are limited in their matching abilities. The module fnmatch has more advanced functions and methods for pattern matching. We will use fnmatch.fnmatch(), a function that supports the use of wildcards such as * and ?, to search for filenames. For example, in order to find all .py files in a directory using fnmatch, you would do the following:

 

import os
import fnmatch

for file_name in os.listdir('routes'):
    if fnmatch.fnmatch(file_name, '*.py'):
        print(file_name)

 

This iterates over the list of files in routes directory and uses fnmatch( ) to perform a wildcard search for files that have the .py extension.

 

Let’s suppose we want to find .txt files that meet certain criteria. For example, we could be only interested in finding .txt files that contain the word data, a number between a set of underscores, and the word backup in their filename. Something similar to data_01_backup, data_02_backup, or data_03_backup. We could write the code as below:

 

for filename in os.listdir('.'):
    if fnmatch.fnmatch(filename, 'data_*_backup.txt'):
        print(filename)