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

2024-03-28 21:22:20 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我想办法解决这个问题吗。在下面的代码中,我将获取一个列表并打开所有的.log和.txt文件,以便在其中搜索特定的字符串。在最内部的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

Tags: 文件path字符串inforoutputifos
1条回答
网友
1楼 · 发布于 2024-03-28 21:22:20

这个怎么样:

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

计数从0开始,并为每个匹配的文件递增。你知道吗

相关问题 更多 >