Looking for a string in text file with python

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

>Solution :

apart from other stuff mentioned in the comments, the problem is here:

    for num, line in enumerate(checked_script, 1):
        if key in line:
            print("OK")
            return 1
        else:
            print("no")
            return 0

If the key is not found in the first line of the file then it will return 0 and not continue with the rest of the loop.

We can just do this:

    for num, line in enumerate(checked_script, 1):
        if key in line:
            print("OK")
            return 1
    print("no")
    return 0

i.e. if the code gets to the end of the for loop without returning (or breaking) early then the key wasn’t found in any of the lines.

Leave a Reply