With Statement - Python (2016)

Python (2016)

CHAPTER 15: With Statement

Just like the try statement, the with statement is meant for error handling. This statement is used to automatically clean up objects. This is helpful in reducing the amount of code that one has to write. It also allows for the omission of the finally statement as well as the manually written cleanup of the object.

In using the with statement, one will need to point to the object that one wishes to use. This is followed by the as statement, which will end with the object’s variable name. The code below is an example that uses this statement, assuming that “Hello world!” is a line that appears in the file “hello.txt|”.

With open (“hello.txt”, “r”) as file:


Hello world!

Here is another example that uses the except, try, and finally statements. Once more, it assumes that the sentence “Hello world!” appears in the “hello.txt” file.


File=open(“hello,txt”, “r”)


except IOError:

Print(“An I/O error just occurred”)


Print(“An unknown error just occurred”)



Hello world!

However, if there is an error while the file is still open, in this case it will not close. In other circumstances, one would have to write using a try...finally block to make sure that there is a proper object cleanup. However, this would need quite a lot of additional work while sacrificing readability at the same time.