views:

190

answers:

3
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("Hello Python!\n")
f.close()

What's the advantage of using open .. as instead of f = ? Is it just syntactic sugar? Just saving one line of code?

+2  A: 

The former still closes f if an exception occurs during the f.write().

djc
+10  A: 

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.

Kathy Van Stone
+12  A: 

The with statement is important in resource acquisition, but first of all is not the same code you wrote, but is more near this one:

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

While this can seems only a syntactic sugar, is really important on release resources. Generally the world is more complex than that example and you can forgot a try.. except... or you don't handle an extreme case and the resource is never freed.

For a complete explanation, look at the 343 pep, it is plenty of examples.

mg
it's `except`, not `catch`
SilentGhost
@SilentGhost: thanks.
mg