在Python中使用'with ... as'语句有什么好处?

pro*_*eek 19 python with-statement

with open("hello.txt", "wb") as f:
    f.write("Hello Python!\n")

好像是一样的

f = open("hello.txt", "wb")
f.write("Hello Python!\n")
f.close()
Run Code Online (Sandbox Code Playgroud)

使用open ...而不是f =有什么好处?它只是语法糖吗?只需保存一行代码?

mg.*_*mg. 26

为了等同于with语句版本,您编写的代码应该看起来像这样:

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

虽然这可能看起来像语法糖,但它确保您释放资源.一般来说,这个世界比这些人为的例子更复杂,如果你忘记了try.. except...或者没有处理极端情况,你手上就会有资源泄漏.

with语句可以避免这些泄漏,从而更容易编写干净的代码.有关完整的解释,请参阅PEP 343,它有很多例子.


Kat*_*one 13

如果f.write抛出异常,f.close()则在使用时with调用,而在第二种情况下不调用.还f具有较小的范围,使用时代码更清晰with.