Using python “with” statement with try-except block

后端 未结 4 574
太阳男子
太阳男子 2020-12-02 06:53

Is this the right way to use the python \"with\" statement in combination with a try-except block?:

try:
    with open(\"file\", \"r\") as f:
        line =          


        
4条回答
  •  旧巷少年郎
    2020-12-02 07:32

    1. The two code blocks you gave are not equivalent
    2. The code you described as old way of doing things has a serious bug: in case opening the file fails you will get a second exception in the finally clause because f is not bound.

    The equivalent old style code would be:

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

    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.

提交回复
热议问题