Using file-like objects

Let's exploit this polymorphism across file-like objects by writing a function to count the number of words per line in a file and return that information as a list:

>>> def words_per_line(flo):
... return [len(line.split()) for line in flo.readlines()]

Now we'll open a regular text file containing the fragment of T.S. Eliot's masterpiece we created earlier, and pass it to our new function:

>>> with open("wasteland.txt", mode='rt', encoding='utf-8') as real_file:
... wpl = words_per_line(real_file)
...
>>> wpl
[9, 8, 9, 9]

The actual type of real_file is:

>>> type(real_file)
<class '_io.TextIOWrapper'>

But you shouldn't normally concern yourself with this specific type; is an internal
Python implementation detail. You're just care that it behaves "like a file".

We'll now do the same using a file-like object representing a web resource referred to by a URL:

>>> from urllib.request import urlopen
>>> with urlopen("http://sixty-north.com/c/t.txt") as web_file:
... wpl = words_per_line(web_file)
...
>>> wpl
[6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 7, 8, 14, 12, 8]

The type of web_file is quite different from what we just saw:

>>> type(web_file)
<class 'http.client.HTTPResponse'>

However, since they are both file-like objects, our function can work with both.

There's nothing magical about file-like objects; it's just a convenient and fairly informal description for a set of expectations we can place on an object which are exploited through duck-typing.

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

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