Equivalent ways to json.load a file in python?
<p>I often see this in code:</p>

<pre><code>with open(file_path) as f:
    json_content = json.load(f)
</code></pre>

<p>And less often this:</p>

<pre><code>json_content = json.load(open(file_path))
</code></pre>

<p>I was wondering if the latter is an anti pattern or what the difference between the two versions is.</p>

<p><code>json.load(open(file_path))</code> relies on the GC to close the file. That's not a good idea: If someone doesn't use CPython the garbage collector might not be using refcounting (which collects unreferenced objects immediately) but e.g. collect garbage only after some time.</p>

<p>Since file handles are closed when the associated object is garbage collected or closed explicitly (<code>.close()</code> or <code>.__exit__()</code> from a context manager) the file will remain open until the GC kicks in.</p>

<p>Using <code>with</code> ensures the file is closed as soon as the block is left - even if an exception happens inside that block, so it should always be preferred for any real application.</p>

python contextmanager