Codelife Codelife - 6 months ago 12
Python Question

Search string in text file : name not defined error python3

Hi I want to search a string in a text file using python. I am using python3.

Here is my code :-

def check():
datafile = open('testfile.txt')
found = False
for line in datafile:
if good in line:
found = True
break

return found

found = check()
if found:
print ("String found")
else:
print ("not found")


Here testfile.txt is a text file which contains the string "good". So, expected output should be "String found". But, it is showing error "NameError: name 'good' is not defined'.

Answer

You have forgotten to put quotes around what you want to be a string.
Changing good to either 'good' or "good" will fix your problem.

There are some other problems with this code though, you are forgetting to close the file for one.
Your code should look more like:

def check():
    with open('testfile.txt') as datafile:
        found = False
        for line in datafile:
            if 'good' in line:
                found = True
                break
    return found

If you edit python in an IDE ( such as IDLE ) you will notice mistakes like these easier because syntax highlighting will usually highlight the string, but not highlight variable names.