#!/usr/bin/python3 # =================================================================== # search multiple directories for regular files that match # one of multiple file name patterns (regular expression) # =================================================================== import re import os pats = [r'\.html$', r'\.py$', r'\.txt$' ] # list of # file name patterns dirs = ['.', './z'] # list of directories # ------------------------------------------------------------------- # create a list of all file names that match a specified pattern # in a directory # # dirs list of directories to search # pats list of regexp to match file names # lst returned list of files names (path + name) # ------------------------------------------------------------------- def list_of_files(dirs,pats): lst = [] # ---- for each directory for d in dirs: # ---- names of files in directory fils = os.listdir(d) # ---- directory (path) must end in '/' if not re.search('\/$',d): d = d + '/' for f in fils: # ---- file path + name ff = d + f # ---- regular file? if not os.path.isfile(ff): continue # ---- file name matches a pattern? for p in pats: if re.search(p,f): # ---- save absolute path + name lst.append(os.path.abspath(ff))) break return lst # ------------------------------------------------------------------- # ---- main # ------------------------------------------------------------------- if __name__ == '__main__': lst = list_of_files(dirs,pats) # get list of files print(sorted(lst)) # print sorted file list