This is a function for finding files in a folder and its subdirectories. Search patterns must be given in a list. Patterns can follow the unix shell standard (default) or regular expressions (via argument ‘regex’). The argument ‘recursive’ decides whether search is done recursively in all subdirectories or in the defined directory only. The output is a list containing the full names (including the full directory name) of all files/folders matching the defined pattern(s).

foldermodes: 0: no folders 1: folders included 2: only folders

import os
import re
import fnmatch

def dissolve(inlist):
    list and tuple flattening; e.g. [[1, 2], [3, 4]] -> [1, 2, 3, 4]
    out = []
    for i in inlist:
        i = list(i) if type(i) is tuple else i
        out.extend(dissolve(i)) if type(i) is list else out.append(i)
    return out

def finder(folder, matchlist, foldermode=0, regex=False, recursive=True):
    # match patterns
    pattern = r'|'.join(matchlist if regex else [fnmatch.translate(x) for x in matchlist])
    if recursive:
        out = dissolve([[os.path.join(root, x) for x in dirs+files if, x)] 
                  for root, dirs, files in os.walk(folder)])
        out = [os.path.join(folder, x) for x in os.listdir(folder) if, x)]
    # exclude directories
    if foldermode == 0:
        out = [x for x in out if not os.path.isdir(x)]
    if foldermode == 2:
        out = [x for x in out if os.path.isdir(x)]
    return sorted(out)


>>>finder('D:/test', ['^[A-Z]{2-3}_[0-9]{9}\.(?:tif|envi)$'], regex=True)
>>>finder('D:/test', ['*.hdr', '*.tif'])