I have written a Python function which matches all files in the current directory with a list of extension names. It is working correctly.
import os, sys, time, re, stat
def matchextname(extnames, filename):
# Need to build the regular expression from the list
myregstring = ""
for index in range(len(extnames)):
# r1 union r2 and so on operator is pipe(|)
# $ is to match from the end
if index < len(extnames) - 1:
myregstring = myregstring + extnames[index] + '$' + '|'
else:
myregstring = myregstring + extnames[index] + '$'
# getting regexobject
myregexobj = re.compile(myregstring)
# Now search
searchstat = myregexobj.search(filename)
if searchstat:
print 'Regex', filename
It is called like this:
if __name__ == '__main__':
fileextensions = ['\.doc', '\.o', '\.out', '\.c', '\.h']
try:
currentdir = os.getcwd()
except OSError:
print 'Error occured while getting current directory'
sys.exit(1)
for myfiles in os.listdir(currentdir):
matchextname(fileextensions, myfiles)
Could you please review the code and suggest if there is any better way of doing this, or share any other comments related to errors/exception handling which are missing - or anything else in terms of logic?