Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 354
prosseek Avatar asked Apr 29 '10 14:04

prosseek


People also ask

What is the use of with as in Python?

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.

What is the advantage of using with statement to open a text file?

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.

What is the advantage of using with keyword?

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.

What is an advantage of having with clause while handling a file?

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”.


1 Answers

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.

like image 189
mg. Avatar answered Oct 24 '22 20:10

mg.