ThatDaven
ThatDaven

Reputation: 27

How to search for word in text file and print the entire line with Python?

The code i have right:

with open("text.txt") as openfile:
    for line in openfile:
        for part in line.split():
            if "Hello" in part:
                print(part)

Can only find a specific word like hello in the text an print it. The problem is, i want it to stop printing only that word and print the entire line that has the word in it. How can i do that?

This is the result im getting right now:

hello
hello
hello

Whreas, the text document includes:

hello, i am a code
hello, i am a coder
hello, i am a virus

Upvotes: 1

Views: 3267

Answers (2)

Yossi Levi
Yossi Levi

Reputation: 1268

Pay attention that the word "hello" is LowerCase in your example, therefore, for catching also upper and lowercases I would recommend this modified piece of code:

with open("text.txt") as openfile:
    for line in openfile:
        if "hello" in line.lower():
            print(line)

Upvotes: 3

Gustave Coste
Gustave Coste

Reputation: 707

You just do a non necessary for loop, try this:

with open("text.txt") as openfile:
    for line in openfile:
        if "Hello" in line:
            print(line)

Upvotes: 5

Related Questions