What's the advantage of using 'with .. as' statement in Python?
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? mg. 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