4

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?

2
  • Try this if ! lines.find("Hey"): Commented May 12, 2020 at 23:55
  • 6
    Don't try that. Try reading the docs for the find method: "Return the lowest index in S where substring sub is found...Return -1 on failure." That means if it's at the beginning of the string, find returns 0. So you want if lines.find(...) >= 0. Commented May 12, 2020 at 23:56

3 Answers 3

5

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:

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

Comments

4

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)

Comments

1

.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.

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.