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.txt
说记录失败测试所以如何让它注意到“测试”,这样如果文本没有任何其他字符,它应该只打印输出记录失败?
编辑: 抱歉英文不好,我的意思是:如果input1.txt只有“登录失败”,那么它应该打印出'文件说出来'。如果它有任何其他字符(例如'logging faaaailed'或'logging failed1',那么它应该打印出'它没有说记录失败'。现在它只是读取记录失败并忽略input1中的任何其他字符.TXT
答案 0 :(得分:1)
也许我错过了什么,但为什么你不能明确地将行与字符串"记录失败" 进行比较?
例如。
if row == "logging failed"
答案 1 :(得分:0)
您可以尝试以下内容:
if row.find('logging') != -1 and row.endswith('failedtest'):
答案 2 :(得分: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