为什么循环搜索文件中存在的字符串 returns True for first iteration 而 False for the rest?

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

我有一个名为 text.txt 的文件,其中包含以下数据:

My
Name
Is
Lorem
Ipsum

我的python代码:

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

输出:

True
False
False
False
False

为什么只有当 i=0 时输出为 True?

如何使所有迭代都为真?我不想在任何地方存储文件的内容!

您在第一次测试时使用了您的文件,因此您在其他迭代中处于文件末尾。

您可以将内容读取为字符串,但由于您不想存储文件,我建议改为 seek 到文件开头:

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

因为它是通过文件来检查的。第一次迭代后,您位于文件末尾。如果你想再次读取文件,你可以 seek() 到文件的开头。

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