File I/O

Throughout the semester, will will learn several ways to receive input from a user or the computer. So far, we have passed arguments to a function and used the input command. In this lecture, we will read in data from two types of files: a plain text file and a comma-separated values (CSV)file. 

Reading plain text files is very straightforward using Python. We simply need to open the file by telling it the location of the file and the file encoding. Then, we can use a for-loopto read the file line by line. CSV files are read in a similar manner; however, we need to import an additional module, csv. Then, to read each line, we use the function csvreaderlocated in the csvmodule. The csvreaderfunction needs to know what file it is reading, the delimiting character (delimiter), and the quotation character (quotechar). The function reads in the file line by line, storing each value in the order in which it appears in a list.

Below, are two examples of functions which read in text and comma-separated value files, respectively.

In this example, we look at counting the number of word occurrences. Programs might want to do something similar when looking for data trends. This method implements a dictionary to keep track of the number of occurrences.

css.php