Using a context manager to open a file

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.py
with 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 ends. The open function is capable of producing a file object when invoked by a context manager, but the true beauty of it lies in the fact that fh.close() will be called automatically for us, even in case of errors.

Context managers are used in several different scenarios, such as thread synchronization, closure of files or other objects, and management of network and database connections. You can find information about them in the contextlib documentation page (https://docs.python.org/3.7/library/contextlib.html).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.174.168