title: How "with" is better than try/catch to open a file in Python?
body: <p>I got that the <code>with</code> statement help you to turn this:</p>
  <pre><code>try:
      f = open(my_file)
      do_stuff_that_fails()
  except:
      pass
  finally:
      f.close()
  </code></pre>
  <p>Into:</p>
  <pre><code>with open(my_file) as f:
      do_stuff_that_fails()
  </code></pre>
  <p>But how is that better? You still have to handle the case with the file not being able to be opened (like prompting the user to tell him he doesn't have permissions), so in reality you'd have:</p>
  <pre><code>try:
      with open(my_file) as f:
          do_stuff_that_fails()
  except (IOError, OSError, Failure) as e:
      do_stuff_when_it_doesnt_work()
  </code></pre>
  <p>Which is equivalent to:</p>
  <pre><code>try:
      f = open(my_file)
      do_stuff_that_fails()
  except (IOError, OSError, Faillure) as e:
      do_stuff_when_it_doesnt_work()
  finally:
      f.close()
  </code></pre>
  <p>Yes, you gained two lines, but you added a level of nesting which doesn't make it easier to read. Is the purpose of the <code>with</code> statement to save you two lines or am I missing something?</p>
  <p>It seems a lot to add a keyword just for that, so I feel like there is some syntax to handle the additional try/except that I don't know about.</p>