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>When you use a context manager, it guarantees that your file will be close automatically at the end of block. The <a href="https://docs.python.org/3.5/reference/compound_stmts.html#with" rel="nofollow"><code>with</code> statement</a> does this by calling the <code>close</code> attribute of the file object, using its <code>__exit__()</code> method. </p>

<p>As said in document:</p>

<blockquote>
  <p>The with statement guarantees that if the <code>__enter__()</code> method returns
  without an error, then <code>__exit__()</code> will always be called.</p>
</blockquote>

<p>Read about more features <a href="https://docs.python.org/3.5/reference/compound_stmts.html#with" rel="nofollow">https://docs.python.org/3.5/reference/compound_stmts.html#with</a></p>

python contextmanager