1

I have to run an if query multiple times. Now of course I could include the query several times in my code. Is this the clean way? Or should I write this differently?

Here my query

if 'xyc_begin' in content and 'xyc_end' in content:
    file.write('xyc available\n')
else:
    print('xyc not available\n')
    file.write('xyc not available\n')
    file.close()
    sys.exit()

Now I would have to check for abc and def (instead of xyc) and adjust the line in the file accordingly. How do you program this correctly or do you just do several queries?

1 Answer 1

1

Put it into a list:

content = "aaa xyc_begin xyc_end    def_begin def_end   bfasfsdnfl"

look_out_for = ["xyc","abc","def"]

with open("f.txt","w") as f:
    for what in look_out_for:
        if f"{what}_begin" in content and f"{what}_end" in content:
            f.write(f"{what} available\n")
        else:
            f.write(f"{what} NOT available\n") 

print(open("f.txt").read())

File content:

xyc available
abc NOT available
def available
Sign up to request clarification or add additional context in comments.

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.