December 2018
Beginner to intermediate
796 pages
19h 54m
English
Let's admit it: the prospect of having to disseminate our code with try/finally blocks is not one of the best. As usual, Python gives us a much nicer way to open a file in a secure fashion: by using a context manager. Let's see the code first:
# files/open_with.pywith open('fear.txt') as fh: for line in fh: print(line.strip())
The previous example is equivalent to the one before it, but reads so much better. The with statement supports the concept of a runtime context defined by a context manager. This is implemented using a pair of methods, __enter__ and __exit__, that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ...
Read now
Unlock full access