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>In addition to other answers, a context manager is very similar to the try-finally clause.</p>

<p>This code:</p>

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

<p>can be written as:</p>

<pre><code>f = open(file_path)
try:
    json_content = json.load(f)
finally:
    f.close()
</code></pre>

<p>The former is clearly preferable.</p>

python contextmanager