Indomart Indomart -4 years ago 127
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
return found

found = check()
if found:
print ("Success")
print ("Fail")

Here is the result if the keyword is not found:

Traceback (most recent call last):
File "", line 26, in <module>
found = check()
File "", line 24, in check
return found
UnboundLocalError: local variable 'found' referenced before assignment"""

Answer Source

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>
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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download