1

I am learning how to read txt files and find something in them. The example below outputs the entire txt file. I am trying to get it to print out "found it" when it finds the word "thanks" in the txt file. Where am I wrong?

This is the txt file I am reading:

this is a
demo file
for exercises
thanks
bye

This is the code I have written:

f = open("demo.txt", "r")
print(f.readline())
print(f.readline())

for word in f:
    print(word)
    if word == "thanks":
        print("found it")

This is the output:

this is a

demo file

for exercises

thanks

bye



Process finished with exit code 0
3
  • 3
    Your line is thanks\n meaning it contains newline. Change == into in. Commented Sep 19, 2019 at 8:44
  • On everyline there is a special character at the end of the line for new line (\n). So you can use ` if "thanks" in word: ` or strip the word using word.strip() to remove trailing space and new line character. Commented Sep 19, 2019 at 8:53
  • Thank you @syedjafer, this is the only solution that worked! Commented Sep 19, 2019 at 9:36

2 Answers 2

1
with open("demo.txt", "r") as f:
    for word in f:
        print(word)
        if "thanks" in word:
            print("found it")
            break
Sign up to request clarification or add additional context in comments.

3 Comments

file.readlines() loads the whole file in memory, which is a potential issue if file is huge, and is not necessary anyway, files are iterable so the preferred solution is, plain simply, for line in f: (nb also notice that those are lines, not "words")
@brunodesthuilliers you are right about huge files but I think he is testing on small files considering his example. However I changed it to what you said. Also I used word because I worked on his example so I used same variable name.
the fact the OP is testing on a small file doesn't mean he shouldn't learn to do things the proper way. 20 years ago no one in his own mind would ever consider reading a whole file in memorry at once, and while we now have huge ram space, available meory can still be an issue and break a production server (think about what happens when you have hundreds of processes running parallel, each acting as if it was alone on the server).
0

Files are iterable, so if you want to read a text file line by line, all you have to do is iterate over it. Also, you must ensure the file is closed after use - which is easily done using the with statement. And, finally, lines ends with the (system-dependant) newline marker, which you may want to strip for comparisons.

IOW, your code should look something like:

# nb: "r" (read) is the default
with open("path/to/your/file") as f:
    for line in f:
        # removes the ending newline marker 
        line = line.rstrip("\n") 
        print(line)
        # given your spec 'when it finds the word "thanks"'
        # I assume that it doesn't matter if there's
        # something else in the line, so we test for
        # containment.
        if "thanks" in line:
            print("found it")

2 Comments

Thank you everyone for your help!
@nephele you're welcome - but the way to thank someone for a useful answer is to upvote the answer (and eventually accept the one you deem as best) ;-)

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.