为什么判断字段是否在文本中时,if和else不能同时用呢?只用if,可以if下的print,但是用了else,就全部输出else下的print!
def check(str):
with open(r'C:\Users\yida\Desktop\feedslogcat\1.txt') as f_r:
for line in f_r.readlines():
if str in line:
return print(line)
else:
return print(str,':','字段不存在!')
r1 = str('Boot')
r2 = str('Begin construct Feeds')
check(r1)
check(r2)
或者不用return,也是不行的
def check(str):
with open(r'C:\Users\yida\Desktop\feedslogcat\1.txt') as f_r:
for line in f_r.readlines():
if str in line:
print(line)
break
else:
print(str,':','字段不存在!')
break
把if else 里的return全部删掉,有了return,每次满足条件就退出函数了,根本不会运行你的for循环
把else里面的break去掉试试
我觉得不应该是break应该是continue吧
def check(str):
with open(r'C:\Users\yida\Desktop\feedslogcat\1.txt') as f_r:
for line in f_r.readlines():
if str in line:
print(line)
return
else:
print(str,':','字段不存在!')
return
return和break会导致从你的if-else判断中直接跳出,如果想继续执行循环应使用continue跳出本次循环,如果希望if-else都执行去掉break和return
没搞懂你为何要用else,你遍历每一行的时候,判断不过的时候肯定每次走else逻辑打印很多不存在的信息
def check(str):
with open(r'C:\Users\yida\Desktop\feedslogcat\1.txt') as f_r:
is_exist = False
for line in f_r.readlines():
if str in line:
is_exist = True
print(line)
if not is_exist:
print('不存在')
没明白你的意思,按照我测试的结果,在for循环中,如果存在if下面会打印,不存在else下面也会打印
def check(str):
with open(r'1.txt') as f_r:
for line in f_r.readlines():
if str in line:
print(line)
else:
print(str,':','字段不存在!')
r1 = str('Boot')
r2 = str('Begin construct Feeds')
check(r1)