A function to check all files in a folder against a given pattern.
Uses RegEx for the file pattern.
Returns “true” or “false” for each file.
Usage: FileMatch(“/path/to/folder”, “[a-z0-9]\.exe”, [bool], [bool])
Attributes: Folder path, pattern, recurse, display result
# Import the basics
import io
import os
import re
# r=True will recursively search sub folders as well
# v=True will print the results of the search
def FileMatch(aFolder, aPattern, r=False, v=False):
validArgs = True
if not os.path.isdir(aFolder):
if v: print(aFolder, "is not a valid directory")
validArgs = False
try:
cPattern = re.compile(aPattern)
except Exception as e:
if v: print(e)
validArgs = False
if validArgs:
if v: print("Checking:", aFolder)
passed = []
failed = []
for item in os.listdir(aFolder):
currPath = os.path.join(aFolder,item)
currFile = {}
if os.path.isdir(currPath) and r==True:
thing1, thing2 = checkFolder(currPath,r)
passed.extend(thing1)
failed.extend(thing2)
elif os.path.isfile(currPath) and cPattern.match(item):
if r:
ritem = os.path.join(aFolder,item)
if v: print("Passed:", ritem)
passed.append(ritem)
else:
if v: print("Passed:", item)
passed.append(item)
elif os.path.isfile(currPath) and not cPattern.match(item):
if r:
ritem = os.path.join(aFolder,item)
if v: print("Failed:", ritem)
failed.append(ritem)
else:
if v: print("Failed:", item)
failed.append(item)
else:
if v: print(item, "is neither a file nor a folder")
return passed, failed
else:
return False
