如何在循环范围内获取值并在Python循环外使用它

时间:2011-08-24 18:01:36

标签: python for-loop

有人可以协助我思考这个问题。在下面的代码中,我将列出并打开所有.log和.txt文件,以便搜索特定字符串。在内部最for for循环中,有一个if和else语句,用于确定是否找到了字符串。我想计算一个字符串在...中匹配的文件数,并且某种方式将其传递给第三个(最后一个)for循环和显示...(例如,文件匹配:4)。我还在学习python,所以我没有意识到可以加快这项努力的所有不同结构。我确信这是一个直截了当的问题,但除了死记硬背试验和错误之外,我已经筋疲力尽了我所知道的一切。谢谢!

...

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

1 个答案:

答案 0 :(得分:4)

这个怎么样:

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从0开始,并为每个匹配的文件递增。