I am trying to understand the with statement in python but I don't get how it does exception handling.
For example, we have this code
file = open('file-path', 'w')
try:
file.write('Lorem ipsum')
finally:
file.close()
and then this code
with open('file_path', 'w') as file:
file.write('hello world !')
Here when is file.close() is called? From this question I think because python have entry and exit function (and exit function is called by itself when file.write(); is over?) but then how are we going to do exception handling (catch) statement in particular?
Also, what if we don't write finally in first snippet, it won't close connection by itself?
file = open('file-path', 'w')
try:
file.write('Lorem ipsum')
withblock executes an exit function at the end of the block. In the case of a file handler, the exit function closes the file. No exception happening here. What you do withtry..finallyis simply ensure thatfile.closewill always be called, even if an exception should happen infile.write. Awithblock as the same effect.trywithout anexceptorfinallyblock is a syntax error BTW…