Will file be closed after "open(file_name, 'w+').write(somestr)"
<p>I'm new to python.</p>

<p>I wonder if I write:</p>

<pre><code>open('/tmp/xxx.txt', 'w+').write('aabb')
</code></pre>

<p>Will the file be still opened or closed?</p>

<p>In another word, what's the difference between the above and</p>

<pre><code>with open('/tmp/xxx.txt', 'w+') as f:
  f.write('aabb')
</code></pre>

<p>The file might stay open.</p>

<p>Keep in mind that it <strong>will</strong> be automatically closed upon garbage collection or software termination but it's a bad practice to count on it as exceptions, frames or even delayed GC might keep it open.</p>

<p>Also, you might lose data if the program terminated unexpectedly and you don't <code>flush()</code> it.</p>

<hr>

<p>In many distributions of python, where the GC is different (PyParallel for example) it might cause a big problem.</p>

<p>Even in CPython, it might still stay open in case of frame reference for example. Try running this:</p>

<pre><code>import sys
glob_list = []

def func(*args, **kwargs):
    glob_list.append((args, kwargs))
    return func

sys.settrace(func)

open('/tmp/xxx.txt', 'w+').write('aabb')
</code></pre>

python