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
How about this:
count = 0
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:
count += 1
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: "+str(count)) # here is where I want to show the number of files matched
break
count starts at 0 and increments for every file that there is a match for.
精彩评论