Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation of IF statement in Python

Please help me try to understand the evaluation of this script. It must be something simple I'm not understanding. I want to scan a text file and output lines with specific string value.

So for example my txt file will contain simple stuff:

beep
boop 
bop 
Hey 
beep
boop
bop

and the script is looking for the line with "Hey" and trying to output that line

file_path = "C:\\downloads\\test.txt"
i = 0
file_in = open(file_path,"r+") # read & write
for lines in file_in.readlines():
    i+=1
    #if lines.rfind("this entity will be skipped..."):
    if lines.find("Hey"):
        print(i, lines)
file_in.close()

For some reason it outputs every line except the one it found a match on. How is this possible?

like image 582
wetin Avatar asked Dec 22 '22 18:12

wetin


1 Answers

It's probably more straightforward to do if "Hey" in lines: instead of if lines.find("Hey"):. If you really want to use find(), you could do this: if lines.find("Hey") != -1:

like image 121
Daniel Giger Avatar answered Jan 08 '23 04:01

Daniel Giger