knerr cs21 notes...
back to schedule
WEEK07: File I/O, top-down design
---------------------------------------------------------------
M: File Input/Output
ANNOUNCEMENTS:
- Lab 6 due Thursday night
REVIEW:
- we looked at /home/jk/inclass/coinflip.py, just to review randrange
FILE I/O:
- here's how to open a file for writing (note: myfile is a variable
name that I choose, and "newfile" is the name of the file to write to):
$ python
>>> myfile = open("newfile", 'w')
>>> myfile.write("write this to the file \n")
>>> myfile.write("and this.... \n")
>>> myfile.close()
- and here are the results:
$ cat newfile
write this to the file
and this....
- if you open a file for reading, use 'r' mode:
>>> infile = open("words.txt", 'r')
- note: infile is a variable of type file:
>>> type(infile)
<type 'file'>
- and it can be used as a sequence (in a for loop!):
>>> for line in infile:
... print line
...
happy
birthday
computer
smile
YOUR TURN:
- modify the grade_averageLISTfile.py program to read in grades
from a file....
def readGrades(fname):
"""
read in grades from file, store in a list,
return list back to caller
"""
glist = []
infile = open(fname, 'r')
for line in infile:
grade = float(line.strip())
glist.append(grade)
return glist