简体   繁体   中英

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

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)

Pay attention that the word "hello" is LowerCase in your example, therefor, 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM