Is file automatically closed if read in same line as opening?
<p>If I do (in Python):</p>

<pre><code>text = open("filename").read()
</code></pre>

<p>is the file automatically closed?</p>

<p>In CPython (the reference Python implementation) the file will be automatically closed. CPython destroys objects as soon as they have no references, which happens at the end of the statement at the very latest.</p>

<p>In other Python implementations this may not happen right away since they may rely on the memory management of an underlying virtual machine, or use some other memory management strategy entirely (see PyParallel for an interesting example).</p>

<p>Python, the language, does not specify any particular form of memory management, so you can't rely on the file being closed in the general case. Use the <code>with</code> statement to explicitly specify when it will be closed if you need to rely on it.</p>

<p>In practice, I often use this approach in short-lived scripts where it doesn't really matter when the file gets closed.</p>

python file io