Chapter 10
Reading and Writing Files

Data is often stored in plain-text files, which can be organized in several different ways. For example, the rainfall amounts in Oregon for each separate day in a study period might be stored one value per line in a file, using a newline as a delimiter to separate the values and make the data easier for humans to read. Alternatively, each line might store the values for an entire week or month, separating values within a line using a delimiter such as a space, tab, or comma.

Often, data organization is more complex. For example, a study might keep track of the heights, weights, and ages of the participants. Each record can appear on a line by itself, with the pieces of data in each record separated by delimiters. Some records might even span multiple lines, in which case each record will usually have some kind of a separator (such as a blank line) or use special symbols to mark the start or end of each record.

In this chapter, you’ll learn about different file formats, common ways to organize data, and how to read and write that data using Python. You’ll first learn how to open and read information from files. After that, you’ll learn about the different techniques for writing to files, and then you’ll see several case studies that use the various techniques.