擅长:python、mysql、java
<p>两者<strong>不是</strong>等价的。如果您写<code>out_file = open(to_file, 'w').write(indata)</code>,那么您已经隐式地写了:</p>
<pre><code># equivalent to second code sample
temp = open(to_file, 'w')
out_file = temp.write(indata)
</code></pre>
<p>现在我们可以在<code>write()</code>的<a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow noreferrer">documentation</a>中看到:</p>
<blockquote>
<p><code>f.write(string)</code> writes the contents of string to the file, <strong>returning the number of characters written</strong>.</p>
</blockquote>
<p>所以它返回一个整数。所以在第二个示例中,<code>out_file</code>是一个<em>不是</em>文件处理程序,而是一个整数。在代码的进一步部分,您的目标是使用<code>out_file.close()</code>关闭<code>out_file</code>文件处理程序。但是由于<code>out_file</code>不再是文件处理程序,因此对此调用close没有意义。在</p>
<p>然而,通过使用上下文,您不再需要自己执行<code>.close()</code>,因此更优雅的做法可能是:</p>
^{pr2}$
<p>书本身的减少是允许的(至少从语义上来说,最好使用上下文管理器),因为作者可能从未显式关闭文件句柄。在</p>