0
import os
fname = "input1.txt"

if os.path.isfile(fname):
        f = open("input1.txt", "r")

    for row in f.readlines():
            if "logging failed" in row:
                    print "the file does say 'logging failed' in it"
            else:
                    print "the file doesn\'t say 'logging failed' in it"

input1.txtlogging failedtest那么我怎样才能让它注意到“测试”,以便它应该只在文本没有任何其他字符的情况下打印输出日志记录失败?

编辑:抱歉英语不好,我的意思是:如果 input1.txt 只有“记录失败”,那么它应该打印出“文件确实说它”。如果它有任何其他字符(例如'logging faaaailed'或'logging failed1',那么它应该打印出'it doesn't say logging failed'。现在它只是读取记录失败并忽略输入中的任何其他字符1 。文本

4

3 回答 3

1

也许我遗漏了一些东西,但你为什么不能明确地将row与字符串"logging failed"进行比较?

例如。 if row == "logging failed"

于 2014-03-24T09:17:44.110 回答
0

您可以尝试以下方法:

if row.find('logging') != -1 and row.endswith('failedtest'):
于 2014-03-24T09:20:02.407 回答
0

尝试这个row.count("logging failed") > 0

import os
fname = "input1.txt"

if os.path.isfile(fname):
        f = open("input1.txt", "r")

    for row in f.readlines():
            if row.count("logging failed") > 0:
                    print "the file does say 'logging failed' in it"
            else:
                    print "the file doesn\'t say 'logging failed' in it"

样品测试:

In [4]: t = "the file does say 'logging failed' in it"

In [5]: t.count('logging failed')
Out[5]: 1
于 2014-03-24T09:20:17.493 回答