Reading text files
After searching for a particular file, the next typical action is to open it and read its content. Text files are very simple yet very powerful files. They store data in plain text, without complicated binary formats.
Text file support is provided natively in Python, and it's easy to consider it a collection of lines that can be represented as Python strings.
Getting ready
We'll read the zen_of_python.txt
file, containing The Zen of Python by Tim Peters, which is a collection of aphorisms that very well describe the design principles behind Python.
It is available in the GitHub repository here: https://github.com/PacktPublishing/Python-Automation-Cookbook-Second-Edition/blob/master/Chapter04/documents/zen_of_python.txt:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special...