"ABC" or "DEF" in line
is evaluated as
("ABC") or ("DEF" in line)
Since "ABC"
is a truthy value, the if condition will be satisfied always. You can fix this problem like this
if "ABC" in line or "DEF" in line:
which will be evaluated like
("ABC" in line) or ("DEF" in line)
So, if the line had either ABC
or DEF
, the condition will be satisfied.
If the number of valid words to be checked is large, it would be inconvenient to write a lengthy if
condition. Instead of that, you should write that condition, with any
function, like this
valid_words = ["ABC", "DEF"]
...
if any(word in line for word in valid_words):
Suggestions:
Avoid using
open
as a variable name, as it will shadow the builtinopen
functionWhen you are dealing with files, make sure that you close the opened files properly or prefer to use
with
statement.