Can someone assist me in thinking my way through this problem. In the code below, I'm taking a list and opening all of the .log and .txt files, as to search them for a particular string. In the inner most for loop there is an if and else statement that determines if a string was found or not. I want to count the number of files that a string was matched in ..., and some kind of way pass that to the third(last) for loop and display ... (eg. Files Matched: 4). I'm still learning python, so I'm unaware of all the different constructs that would expedite this endeavor. I'm sure this is a straight forward problem, but I have exhausted everything I know to do besides rote trial and error. Thanks!
...
for afile in filelist:
(head, filename) = os.path.split(afile)
if afile.endswith(".log") or afile.endswith(".txt"):
f=ftp.open(afile, 'r')
for i, line in enumerate(f.readlines()):
result = regex.search(line)
if result:
ln = str(i)
pathname = os.path.join(afile)
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(ln, pathname, result.group())
hold = output
print output
ftp.get(afile, 'c:\\Extracted\\' + filename)
temp.write(output)
break
else:
print "String Not Found in: " + os.path.join(afile)
temp.write("\nString Not Found: " + os.path.join(afile))
f.close()
for fnum in filelist:
print "\nFiles Searched: ", len(filelist)
print "Files Matched: ", count
num = len(filelist)
temp.write("\n\nFiles Searched: " + '%s\n' % (num))
temp.write("Files Matched: ") # here is where I want to show the number of files matched
break
elsestatement should be lined up with theIf result- since it appears to be for when the regex doesn't match.elseis supposed to be lined up with thefor. It will be entered if thebreakstatement in theforloop is never executed, which would mean that the regex didn't match for any line in the file.