File objects as iterators

The culmination of these increasingly sophisticated text file reading tools is the fact that file objects support the iterator protocol. When you iterate over a file, each iteration yields the next line in the file. This means that they can be used in for-loops and any other place where an iterator can be used. At this point, we'll take the opportunity to create a Python module file files.py:

import sys

def main(filename):
f = open(filename, mode='rt', encoding='utf-8')
for line in f:
print(line)
f.close()

if __name__ == '__main__':
main(sys.argv[1])

We can call this directly from the system command line, passing the name of our text file:

$ python3 files.py wasteland.txt
What are the roots that clutch, what branches grow

Out of this stony rubbish? Son of man,

You cannot say, or guess, for you know only

A heap of broken images, where the sun beats

You'll notice that there are empty lines between each line of the poem. This occurs because each line in the file is terminated by a new line, and then print() adds its own. To fix that, we could use the strip() method to remove the whitespace from the end of each line prior to printing. Instead we'll use the write() method of the stdout stream. This is exactly the same write() method we used to write to the file earlier — and can be used because the stdout stream is itself a file-like object. We get hold of a reference to the stdout stream from the sys module:

import sys

def main(filename):
f = open(filename, mode='rt', encoding='utf-8')
for line in f:
sys.stdout.write(line)
f.close()

if __name__ == '__main__':
main(sys.argv[1])

If we re-run our program we get:

$ python3 files.py wasteland.txt
What are the roots that clutch, what branches grow
Out of this stony rubbish? Son of man,
You cannot say, or guess, for you know only
A heap of broken images, where the sun beats

Now, alas, it's time to move on from one of the most important poems of the twentieth century and get to grips with something almost as exciting, context managers.

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

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