jaxben
jaxben

Reputation: 21

Python: Check if a specific line of text is in a file

I want to have a Python program that will read through a text file, then print whether or not a specific string of text was found in that file.

Here is the code that I can't get working:

f=open("to-read.txt","r")

found = False
for x in f.readlines():
    print(x)
    if x is "Hello, World!" or x is "Hello, World!\n":
        found = True

print(found)

I want the code to print True if Hello, World is on any of the lines in to-read.txt, and False if not.

When I run it, it reads the lines but never finds "Hello, World!".

Upvotes: 0

Views: 3083

Answers (2)

Ghantey
Ghantey

Reputation: 636

You can use in keyword to check if the specific string exists in your file

with open('to-read.txt', 'r') as f:
    lines = [line.strip('\n') for line in f.readlines]    # Getting each line without the new_line '\n'

    if 'Hello, World!' in lines:
        print(True)

    else:
         print(False)

Upvotes: 0

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

with open("to-read.txt", "r") as f:
   found = any("Hello, World!" in x for x in f)

print(found)

or, if you want to make sure the line is exactly "Hello, World!" rather than contains it, you can use ==.

    found = any(x == "Hello, World!\n" for x in f)

or even just

    found = "Hello, World!\n" in f.readlines()

Upvotes: 2

Related Questions