June 2017
Beginner
352 pages
8h 39m
English
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 ...
Read now
Unlock full access