(Jun-02-2019, 08:34 PM)Skaperen Wrote: so if the exception might happen, finally: assures that you can close/teardown while not actually handling the exceptionYes,and we use it all time even if not always see it.
with open()
has been then preferred way do deal with files since it came out in Python 2.5.with open('some_file', 'w') as f: f.write('Hello!')The underlying code is this.
f = open('some_file', 'w') try: f.write('Hello!') finally: f.close()Now is there also
__enter__
and __exit__
special methods to make with
.But the important part is that the file is always closed because of no
except
and finally
(deal with all cases for closing the file).