Class Notes Week 8


Week 8 Topics

Monday Wednesday Friday


We will continue the topics from last week, with a focus on File I/O and lists of lists within our larger program designs.

File Input/Output

Almost all real applications require large amounts of data that can’t be manually entered every time a program runs. Instead, data is stored persistently in files. You use these all the time - Excel spreadsheets store numbers, mp3 files store music, etc. We will work with simple files that store all information as text (i.e., strings).

To open a file, we use the open() method in Python

fileVariable = open("filename.txt","r")

fileVariable will be an object that we use to interact with the opened file.
"filename.txt" would be a string containing the actual name of the file e.g., "cupboard.txt" in the exercise below. The last item, "r", tells Python that you plan to only read from the file (as opposed to opening a file to write to).

To close the file when we are done, we use the close() method on the file:

fileVariable.close()

It is very important to remember to close files as leaving them open locks them from use.

Reading from files

To process files, there are many options:

for line in fileVariable:
  print(line)

Exercise: Shopping list

We will learn how to use files using a simple program that reads a file with all items in a cupboard and prints this out. First, move to this week’s directory and create a file called cupboard.txt

$ cd ~/cs21/inclass/w08-files
$ atom cupboard.txt

Add several food items that may be in your dorm/house and save the file. E.g.,

chocolate
cereal
coffee grounds

Now, let us open shopping.py to first print out the contents of the cupboard and then ask the user to enter items they’d like to buy at the grocery store.

File processing

Reading files utilizes string manipulation. Some useful methods include:

Exercise: Gradebook

The goal of this exercise is to read the quiz scores from a file and output the average score for each student. The file (gradebook.txt) is stored in the following format

Name1 Score1A Score1B Score 1C

with one line per student. We will accomplish the following in quizGrades.py:

  1. Open the file
  2. Read each line from the file
  3. For each line,
  4. Close the file when done

List of lists

In the exercise above, our program is limited by the transient nature of data read from the file. That is, we did not keep the line of data that was processed after each iteration. To do so, we would need to put items in a list (one per line). However, the data we have read is a list of information itself. We will see how we can build a list of lists and index into it.

Exercise: Gradebook with lists

In w08-files/grade_list.py, we have a version of quizGrades.py but with added capabilities. The program reads the same file, but now stores it as a list of lists. We will do the following exercises:

  1. With your neighbor, determine how you would access the first student’s name and quiz scores using indexing.
  2. How would you access the 5th student’s 3rd quiz score?
  3. Using this knowledge, we will implement a function to print a particular student’s score on all quizzes.
  4. Implement printQuizScores, which will print all of the students’ score for one particular quiz.

Flashcards Exercise

Let us bring the core concepts of the past two weeks together for our final exercise. You will write a flashcard program that can be used to help study a foreign language. Here is an example run of such a program (user input in bold):

$ python3 flashcard.py 
         essen: to eat
        kaufen: to buy
      besuchen: to think
Nope...besuchen = to visit
        fahren: to travel
        lieben: to love
      schlafen: to sleep
       spielen: to run
Nope...spielen = to play
       trinken: to drink
     verstehen: to understand
==============================

Number correct: 7  (out of 9)
Not bad.

Your program has access to a file, german.txt, that you should read in to get the words and translations. Each line of the file has a German word and its English translation. Here is what the file looks like (german.txt in your w08-files directory):

essen,to eat
kaufen,to buy
besuchen,to visit
fahren,to travel
lieben,to love
schlafen,to sleep
spielen,to play
trinken,to drink
verstehen,to understand

Complete the following:

  1. On paper, work out a design for your solution. Be sure to define what functions you need, the data (parameters) you need to send in, and any return values.
  2. When the initial design is done, proceed to prototyping your design and put control flow in your program. Flag a ninja or myself to review your design (if you are comfortable with the design, proceed to implementation).
  3. Begin your bottom-up implementation. Be sure to test each function thoroughly before moving on.