Reputation: 438
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?
Upvotes: 4
Views: 72
Reputation: 15738
While Daniel's answer is, of course, correct and should be accepted, I want to fuel my OCD and offer some improvements:
# use context managers to automatically release file handler
with open(file_path) as file_in:
# file objects are iterable, will return lines
# reading entire file in memory can crash if file is too big
# enumerate() is a more readable alternative to manual counters
for i, line in enumerate(file_in): # 'line' should be singular
if "Hey" in line: # same as Daniel
print(i, line)
Upvotes: 4
Reputation: 46
.find(sub)
returns an integer - the first index of sub
if sub
is found, and -1 if it is not.
When "Hey" is present, it is at the first index (0), so that is what .find()
returns. Otherwise, "Hey" is not found, so .find()
returns -1.
Since python treats all integers as True except 0, then the conditional evaluates to True when 0 is returned, i.e. when "Hey" is found.
Change your use of .find() to something which fulfills your if statement the way you want.
Upvotes: 1
Reputation: 2533
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:
Upvotes: 5