June 2017
Beginner
352 pages
8h 39m
English
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 sysdef 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.txtWhat are the roots that clutch, what branches ...
Read now
Unlock full access