Indomart Indomart - 22 days ago 10
Python Question

Finding a specific word in a file and return a logical result

I'm a newbie in Python. I'm trying to find a specific word from a file and retun the value success or fail. This script works if the keyword is found but not when the keyword is not found. Thank you for the help.

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")





Here is the result if the keyword is not found:

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"""




Answer

Your problem is that you never initialize found. In your function, your if statement never runs, which means that found is never created. This behavior can be demonstrated with a short example:

>>> if False:
        abc = True


>>> abc
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    abc
NameError: name 'abc' is not defined
>>

This can be fixed by giving found a "default" value before using in your function:

def check():
    found = False
Comments