<p>Python<strong>通常会</strong>垃圾收集对象不再使用,也不再被引用。这意味着完全有可能清理并关闭与垃圾收集器过滤器匹配的打开文件对象。<strong>但是</strong>;您不应依赖于此,而应使用:</p>
<pre><code>with open(..):
</code></pre>
<p><strong>示例</strong>(<em>也是最佳实践</em>):</p>
^{pr2}$
<p><strong>NB:</strong>如果您不关闭文件并将“打开的文件描述符”保留在系统上,那么您最终将开始触及系统的资源限制,特别是“ulimit”。你最终会看到与“打开的文件太多”相关的操作系统错误。(<em>这里假设是Linux,但其他操作系统也会有类似的行为。在</p>
<p><strong>重要提示:</strong>关闭您编写的所有打开的文件也是一个很好的做法,这样您编写的数据就会被正确刷新。这有助于确保数据的完整性,并且不会因为应用程序崩溃而使文件意外地包含损坏的数据。在</p>
<blockquote>
<p>It's worth noting that the above important note is the cause of many issues with where you write to a file; read it back; discover it's empty; but then close your python program; read it in a text editor and realize it's not empty.</p>
</blockquote>
<p><strong>演示:</strong>如果不确保关闭打开的文件,可能会遇到的资源限制和错误的一个很好的示例:</p>
<pre><code>$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> xs = [open("/dev/null", "r") for _ in xrange(100000)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 24] Too many open files: '/dev/null'
</code></pre>