<p>当没有更多行可读取时,<a href="https://docs.python.org/2/library/stdtypes.html#file.readline" rel="nofollow">^{<cd1>} method</a>返回空字符串:</p>
<blockquote>
<p>When <em>size</em> is not 0, an empty string is returned only when EOF is encountered immediately.</p>
</blockquote>
<p>条件测试该结束条件,以结束循环。^只有当<code>in_line</code>是空字符串时,{<cd2>}才为真。Python中的所有“空”值都被认为是false,<code>not</code>操作符将false变成<code>True</code>。参见<a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="nofollow"><em>Truth Value Testing</em> section</a>:</p>
<blockquote>
<p>Any object can be tested for truth value, for use in an <code>if</code> or <code>while</code> condition or as operand of the Boolean operations below. The following values are considered false:</p>
<p>[...]</p>
<ul>
<li>any empty sequence, for example, <code>''</code>, <code>()</code>, <code>[]</code>.</li>
</ul>
</blockquote>
<p>在这里使用<code>while</code>循环实际上过于冗长。通过使用<code>for</code>循环,使文件成为迭代器,可以更简洁地读取文件:</p>
<pre><code>for in_line in in_file:
in_line = in_line.rstrip('\n')
</code></pre>
<p>不能保证一行以换行结束;上面的<code>str.rstrip()</code>调用仅当它实际在那里时才删除它。你知道吗</p>
<p>最后但并非最不重要的一点是,您可以将file对象用作<em>上下文管理器</em>;将open file对象传递给<code>with</code>语句可确保在执行块时,即使发生异常,文件也会再次自动关闭:</p>
<pre><code>with open(filename, "rt") as in_file:
for in_line in in_file:
in_line = in_line.rstrip('\n')
</code></pre>
<p>不再需要单独的<code>in_file.close()</code>调用。你知道吗</p>
<p>另请参见教程中的<a href="https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow"><em>Methods of File Objects</em> section</a>。你知道吗</p>