我是Python的新手。我试图从文件中找到特定的单词并重新调整值成功或失败。如果找到关键字,则此脚本有效,但未找到关键字时则无效。谢谢你的帮助。
def check():
datafile = open('data\CR_Daily201611070011.log')
for line in datafile:
if 'End of CR_Daily' in line:
found = True
break
return found
found = check()
if found:
print ("Success")
else:
print ("Fail")
如果找不到关键字,结果如下:
Traceback (most recent call last):
File "file_reader.py", line 26, in <module>
found = check()
File "file_reader.py", line 24, in check
return found
UnboundLocalError: local variable 'found' referenced before assignment"""
答案 0 :(得分:1)
您的问题是您永远不会初始化found
。在您的函数中,if语句永远不会运行,这意味着永远不会创建found
。可以通过一个简短的示例来演示此行为:
>>> if False:
abc = True
>>> abc
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
abc
NameError: name 'abc' is not defined
>>
这可以通过在函数中使用之前给found
一个“默认”值来修复:
def check():
found = False
答案 1 :(得分:0)
只需在found
开始时指定check()
值:
def check():
found = False
...
答案 2 :(得分:0)
您不需要为找到的值分配值。如果您发现了“CR_Daily结束”,则可以返回 True 。并在for后返回 False 。我重写了你的代码:
def check():
datafile = open('data\CR_Daily201611070011.log')
for line in datafile:
if 'End of CR_Daily' in line:
return True
return False
found = check()
if found:
print ("Success")
else:
print ("Fail")