Will the file be closed after returning from function?
<p>Here is a python function:</p>

<pre><code>def read_data(filename):
    f = zipfile.ZipFile(filename)
    for name in f.namelist():
        return tf.compat.as_str(f.read(name))
    f.close()
</code></pre>

<p>Will the file be closed? There is no error when calling it.</p>

<p>The file won't be closed. If you want to close the file, you can write it like:</p>

<pre><code>def read_data(filename):
    with zipfile.ZipFile(filename) as f:
        for name in f.namelist():
            return tf.compat.as_str(f.read(name))
</code></pre>

<p>Testing your code:
<a href="http://i.stack.imgur.com/JrFKP.png" rel="nofollow"><img src="http://i.stack.imgur.com/JrFKP.png" alt="picture shows that the file wasn&#39;t closed"></a></p>

<p>Testing the code with <code>with</code>:
<a href="http://i.stack.imgur.com/L09WK.png" rel="nofollow"><img src="http://i.stack.imgur.com/L09WK.png" alt="picture shows that the file has been closed"></a></p>

python file zipfile