0

I have a text file that includes a word like "test". Now what i am trying to do is using python i am opening that text file and search for that word. If the word exists then the python program should return exit code 0 or else 1.

This is the code that i have written that returns 0 or 1.

word = "test"

def check():
    with open("tex.txt", "r") as file:
        for line_number, line in enumerate(file, start=1):  
            if word in line:

                return 0
            else:
                return 1

print(check())
output

0

what I want is I want to store this exit code in some variable so that i can pass this to a yaml file. Can someone guide me here how can i store this exit code in a variable? thanks in advance

3
  • 1
    Are you sure your code is indented properly? The way it appears here, it will always return 1 unless the word is in the first line Commented Nov 30, 2022 at 13:47
  • 1
    This program does not what is written in the descripition. return 0 immediately when the word is found in a line, but return 1 only at the end when the whole file has been read without finding the word. Commented Nov 30, 2022 at 13:49
  • yes i want to return 1 if the text is not found in the whole file Commented Nov 30, 2022 at 13:52

1 Answer 1

1

I think you are looking for sys.exit(), but since you edited your question, I am not sure anymore. Try this:

import sys

word = "test"

def check():
    with open("tex.txt", "r") as file:
        for line_number, line in enumerate(file, start=1):  
            if word in line:
                return 0
     
    return 1

is_word_found = check() # store the return value of check() in variable `is_word_found`
print(is_word_found) # prints value of `is_word_found` to standard output
sys.exit(is_word_found) # exit the program with status code `is_word_found`

BTW: as @gimix and @VPfB mentioned, your check() function did return a value immediately after it checked the first line of your file. I included a fix for that, now 1 is returned only if the word is not found is any line of your file.

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

3 Comments

how can i see the output?
what output do you expect?
I want to save the return value in some variable for example a = output and then want to print the variable a

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.