Himanshu Malhotra Himanshu Malhotra - 12 days ago 6
Python Question

Why the loop to search for a string that is present in a file returns True for first iteration and False for the rest?

I have a file named text.txt which contains the following data:

My
Name
Is
Lorem
Ipsum


My python code:

with open("text.txt") as f:
for i in xrange(5):
print "Is\n" in f


Output:

True
False
False
False
False


Why the output is True only when i=0?

What to do to get True for all the iterations? I do not want to store the contents of the file anywhere!

Answer

You're consuming your file at the first test, so you're at the end of the file for the other iterations.

You could read the contents to a string, but since you don't want to store the file, I propose to seek to beginning of the file instead:

with open("test.txt") as f:
    for i in range(5):
        f.seek(0)
        print ("Is\n" in f)