<p>我想逐行读取巨大的文本文件(如果找到“str”的行,则停止)。
如何检查是否到达文件结尾?</p>
<pre><code>fn = 't.log'
f = open(fn, 'r')
while not _is_eof(f): ## how to check that end is reached?
s = f.readline()
print s
if "str" in s: break
</code></pre>
<p>只需遍历文件中的每一行。Python会自动检查文件结尾并为您关闭文件(使用<code>with</code>语法)。</p>
<pre><code>with open('fileName', 'r') as f:
for line in f:
if 'str' in line:
break
</code></pre>