Hi I want to search a string in a text file using python. I am using python3.
Here is my code :-
datafile = open('testfile.txt')
found = False
for line in datafile:
if good in line:
found = True
found = check()
print ("String found")
print ("not found")
You have forgotten to put quotes around what you want to be a string.
good to either
"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.