I can not see why you use enumerate() in your example. The resulting num variable 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 a io.StringIO just for that example code because we don't have a real file here.
#!/usr/bin/env python3
import io
simulated_file_content = "lineA\nMillSet_BBs.set_image_at_end('yes')\nline3"
def check_if_image_at_end_selected():
# io.StringIO just for simulating a file
with io.StringIO(simulated_file_content) as checked_script:
key = "MillSet_BBs.set_image_at_end('yes')"
# read whole file at once
file_content = checked_script.read()
if key in file_content:
print("OK")
return True
else:
print("no")
return False
result = check_if_image_at_end_selected()
print(result)
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 the with block.
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:
#!/usr/bin/env python3
import io
simulated_file_content = "lineA\nMillSet_BBs.set_image_at_end('yes')\nline3"
def check_if_image_at_end_selected():
# io.StringIO just for simulating a file
with io.StringIO(simulated_file_content) as checked_script:
key = "MillSet_BBs.set_image_at_end('yes')"
# read line by line
for line in checked_script.readline():
if key == line:
print("OK")
return True
print("no")
return False
result = check_if_image_at_end_selected()
print(result)
exceptcase in this code, do you mean theelseclause of the if statement in the for loop?with open(...)line should be indented one more level, and you don't need thechecked_script.close()line because that's what thewith open(...)context manager doesTrueorFalseinstead of 0 or 1