WEEK08: more top-down design
---------------------------------------------------------------
F: File I/O (write) and more function practice
OUTPUT to a file:
- 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')
>>> type(myfile)
<type 'file'>
(a new python type!!)
>>> myfile.write("write this to the file \n")
>>> myfile.write("and this.... \n")
>>> myfile.close()
- and here are the results of this:
$ ls
newfile
$ cat newfile
write this to the file
and this....
- what happens if we leave out the \n's on each line??
- if "newfile" exists, and we open it with mode "w", then "newfile"
will be wiped out and overwritten!
- can also use mode "a" to append to a file
MORE FUNCTIONS:
- draw the stack for this one:
def double(L):
"""assume L is a list of numbers, double each"""
for i in range(len(L)):
L[i] = 2*L[i]
>>> L = [2,6,9]
>>> double(L)
>>> print L
[4, 12, 18]