ABSTRACT

Saving the program output to a file is important for archival purposes. It is also useful to ensure reproducibility of your program. Having a copy of your program output always comes in handy. Reading a previously saved file is a must-have feature on almost every computer program. This chapter shows how to read and write any text file. For the purposes of

this book, “reading a text file” is the process of entering the data from a file into a program. The process of understanding the meaning of the data units in the program is called parsing. A simple example will clarify this: A file can have four data units in a line like this:

1,Joe,Doe,1976

When this line is read, Python sees it as one string. So there is a need to take an extra step for the program to recognize each of the four data on it. This step is the parsing. The parsing step depend on the format of the data, so there is no universal method for text parsing. This chapter covers how to parse data separated by a special character such as a comma or the tab character.1