I'm trying to look for a string in text file. Technically, my code supposed to work, I was define a key to search, which is the string I'm looking for and I checked the whole file line after line.
When I'm running the code, somehow the code always go to except case although the results suppose to be "True"
This is my code:
def check_if_image_at_end_selected():
with open('Sanity_CS.txt', 'r') as checked_script:
key = "MillSet_BBs.set_image_at_end('yes')"
for num, line in enumerate(checked_script, 1):
if key in line:
print("OK")
return 1
else:
print("no")
return 0
I can not see why you use
enumerate()in your example. The resultingnumvariable is never used. So I assume the line number is not of interested right?Because of that I removed that part from the code. I replaced the
open()with aio.StringIOjust for that example code because we don't have a real file here.The code just read the whole file at once as one string and then does a simple string search. Nothing more.
You don't have to
close()the file object your self. This is done automatically (by the ContextManager) when you use thewithblock.If you don't want to read the whole file at once because it is a very big file you can do a line by line read-and-search like this: