Hello, World! line 2 --> MrBeast" /> Hello, World! line 2 --> MrBeast" /> Hello, World! line 2 --> MrBeast"/>

Finding a line through a keyword in a multiple line text file using Python

97 Views Asked by At

(using Python 3.12.2) I have a multiplelines file called "text.txt" and it has 3 lines, it goes like this:

line 1 --> Hello, World!

line 2 --> MrBeast is rich.

line 3 --> :3 avg valorant player

However I would like to print only the line that has the "World" independent of the line it is located, which means I have to find the desired line first. I have been searching for a function that would do this for me and have come to the conclusion that there is maybe no such thing as variable.lineindex("desired_string") and will have to code it myself, any suggestions or am I being a moron?

2

There are 2 best solutions below

4
Milos Stojanovic On
desired_string = "World"

with open("text.txt", "r") as file:
    for line_number, line in enumerate(file, 1):
        if desired_string in line:
            print(f"Found '{desired_string}' in line {line_number}: {line.strip()}")

You can break in if block if you need only the first occurence.

2
user16171413 On

You can loop through each line and look for the line that contains your desired string like this:

filepath = "C:\\Users\\John Dee\\Desktop\\text.txt"
with open(filepath, 'r') as file_object:
    for line in file_object:
        print(line if 'World' in line else '')

NB: If using relative file path, then do filepath = text.txt. If using an absolute file path, please note that the file path I used is for Windows.