What's the advantage of using 'with .. as' statement in Python?

前端 未结 3 2132
清酒与你
清酒与你 2020-12-03 14:03
with open(\"hello.txt\", \"wb\") as f:
    f.write(\"Hello Python!\\n\")

seems to be the same as

f = open(\"hello.txt\", \"wb\")
f.write(\"Hell         


        
3条回答
  •  醉梦人生
    2020-12-03 14:21

    In order to be equivalent to the with statement version, the code you wrote should look instead like this:

    f = open("hello.txt", "wb")
    try:
        f.write("Hello Python!\n")
    finally:
        f.close()
    

    While this might seem like syntactic sugar, it ensures that you release resources. Generally the world is more complex than these contrived examples and if you forget a try.. except... or fail to handle an extreme case, you have resource leaks on your hands.

    The with statement saves you from those leaks, making it easier to write clean code. For a complete explanation, look at PEP 343, it has plenty of examples.

提交回复
热议问题