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?
The with statement in Python is used for resource management and exception handling. You'd most likely find it when working with file streams. For example, the statement ensures that the file stream process doesn't block other processes if an exception is raised, but terminates properly.
With the “With” statement, you get better syntax and exceptions handling. “The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.” In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.
Using with means that the file will be closed as soon as you leave the block. This is beneficial because closing a file is something that can easily be forgotten and ties up resources that you no longer need. Note that this isn't specific to Python 3 at all.
Benefits of calling open() using “with statement” When with the block ends, it will automatically close the file. So, it reduces the number of lines of code and reduces the chances of bug. If we have opened a file using “with statement” and an exception comes inside the execution block of “with statement”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With