We will continue the topics from last week, with a focus on File I/O and lists of lists within our larger program designs.
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.
To process files, there are many options:
readline()
- returns the next line of the file (the file object keeps track of where it is in the file)readlines()
- returns a list of strings, which each line of the file as one string in the listfor line in fileVariable:
print(line)
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.
Reading files utilizes string manipulation. Some useful methods include:
rstrip()
- a string method that removes all white space (spaces, enter lines, tabs, etc.) from the end of the string. All lines that are read in have an (invisible) newline character at the end. We’ll need rstrip()
to remove that.split()
- breaks a string into pieces if it has many pieces of information.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
:
rstrip()
split()
split()
returns a list of strings. We’ll need to convert the file contents to their proper type (i.e., scores need to be ints)getAverage()
with the extracted name and scores from the lineIn 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.
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:
printQuizScores
, which will print all of the students’ score for one particular quiz.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: