1

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

6
  • 2
    there is no except case in this code, do you mean the else clause of the if statement in the for loop? Commented Jun 13, 2022 at 10:38
  • 1
    easiest way to format code in SO is to start and end with three back-ticks (```) then you can just copy and paste it without having to change the indentation. Commented Jun 13, 2022 at 10:40
  • 2
    everything after the with open(...) line should be indented one more level, and you don't need the checked_script.close() line because that's what the with open(...) context manager does Commented Jun 13, 2022 at 10:42
  • 2
    Please edit your question instead of answering in comments. Also, do you realize you have a for loop that always returns during the first iteration? (if .. return, else return) Commented Jun 13, 2022 at 10:42
  • 1
    and for better code style you should probably return True or False instead of 0 or 1 Commented Jun 13, 2022 at 10:43

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

When you use with as, you need to tab the next lines, it's just like an if statement. And you don't need to manually close the file after

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.