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

前端 未结 3 2151
清酒与你
清酒与你 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:33

    If f.write throws an exception, f.close() is called when you use with and not called in the second case. Also f has a smaller scope and the code is cleaner when using with.

提交回复
热议问题