为什么第一次返回的计数值是正确的,但是循环?

时间:2012-06-26 14:49:09

标签: python parsing loops

在下面的for循环中,我试图理解为什么count的正确值仅在循环第一次运行时返回。

我正在创建一个解析程序来查找文本文件中的某些字符串并对其进行计数。但是,我在一个地方遇到了一些麻烦。

def callbrowse():
    filename = tkFileDialog.askopenfilename(filetypes = (("Text files", "*.txt"),("HTML files", ".html;*.htm"),("All files", "*.*")))
    print filename
    try:
        global filex
        global writefile
        filex = open(filename, 'r')
        print "Success!!"
        print filename
    except:
        print "Failed to open file"

######This returns the correct count only the first time it is run.  The next time it  ######returns 0.  If the browse button is clicked again, then this function returns the ######correct count again.
def count_errors(error_name):
    count = 0
    for line in filex:
        if error_name == "CPU > 79%":
            stringparse = "Utilization is above"
        elif error_name == "Stuck touchscreen":
            stringparse = "Stuck touchscreen"
        if re.match("(.*)" + "Utilization is above" + "(.*)",line):
            count = count + 1
    return count

感谢您的帮助。我似乎无法使其正常工作。

1 个答案:

答案 0 :(得分:5)

该方法仅在第一次起作用,因为文件是通过结尾传递的。 如果再次调用该方法,则不再有行。 您可以通过在for循环之前调用filex.seek(0)来重置文件位置。