Using python "with" statement with try-except block Using python "with" statement with try-except block python python

Using python "with" statement with try-except block


  1. The two code blocks you gave arenot equivalent
  2. The code you described as old wayof doing things has a serious bug:in case opening the file fails youwill get a second exception in thefinally clause because f is notbound.

The equivalent old style code would be:

try:    f = open("file", "r")    try:        line = f.readline()    finally:        f.close()except IOError:    <whatever>

As you can see, the with statement can make things less error prone. In newer versions of Python (2.7, 3.1), you can also combine multiple expressions in one with statement. For example:

with open("input", "r") as inp, open("output", "w") as out:    out.write(inp.read())

Besides that, I personally regard it as bad habit to catch any exception as early as possible. This is not the purpose of exceptions. If the IO function that can fail is part of a more complicated operation, in most cases the IOError should abort the whole operation and so be handled at an outer level. Using with statements, you can get rid of all these try...finally statements at inner levels.


If the contents of the finally block are determined by the properties of the file object being opened, why shouldn't the implementer of the file object be the one to write the finally block? That's the benefit of the with statement, much more than saving you three lines of code in this particular instance.

And yes, the way you've combined with and try-except is pretty much the only way to do it, as exceptional errors caused within the open statement itself can't be caught within the with block.


I think you got it wrong about "with" statement that it only reduces lines.It actually does initialization and handle teardown.

In your case "with" does

  • open a file,
  • process its contents, and
  • make sure to close it.

Here is link for understanding "with" statement : http://effbot.org/zone/python-with-statement.htm

Edit: Yes your usage of "with" is correct and functionality of both blocks of code is identical.Question about why to use "with" ? it's because of benefits you get with it. like you mentioned about accidentally missing f.close().