Fall 2006 Midterm 2 Review: File Writing
4)
1.
def double (num):
writefile= open("number.txt","wt")
double= num x 2
writefile.write(str(double))
writefile.close()
2.
def lastOne ():
writefile= open("string.txt","rt")
contents= writefile.read()
writefile.close()
return contents[-1]
Stacy Schwaiger
A minor correction, double = num *2 You need to use the asterisk when you type it in JES. The second one is right. - Bobby Mathew |
do you have to use writefile, or is file.close() okay too as long as its consistent
| Yup, file.close() is fine. You can use any word you want as long as its used everywhere in your function. - Bobby Mathew |
If the last character is -1, what is the first character?
| You can access the first character by putting 0 in the place of -1. - Bobby Mathew |
what is the wt and the rt after the XXXXX.txt part in the parenthesis?
| 'wt' stands for write text and 'rt' stands for read text. It just specifies the mode in which the file will be opened. If you know you want to write something to the file, use 'wt'. If you know that the file already exists and you want to read some content off from it, use 'rt'. - Bobby Mathew |
in the second one why do you returned the [-1]?
| The [-1] is the last element in the string. You can use this to access the last element no matter how long the string is. -Brittany Duncan |
what does the str represent in writefile.write(str(double))?
| It turns the number into a string. So if double==42.0, it will write "42.0" Colin Potts |
Link to this Page