I am currently following the same course, and the solution I found was similar to the one ninjagecko used, except that I used only what you were taught in the course so far. My looks like this:
from sys import argv script, filename = argv print "We're going to erase %s." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename, 'w') print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." lines = [raw_input("Lines %r :" % i) for i in range(1, 4)] for line in lines: target.write(line + "\n") print "And finally, we close it." target.close()
It took me a while to copy the parentheses and figure out where to put the formatter and loop, but as soon as I found it, it made sense to me. One important point is the first attempt:
for i in range(1, 4): lines = raw_input("Line %r :" % i)
It appears to work first when the script is run, however, when viewing the target file, it writes only the last line (line3) to the file. I still do not quite understand why this is so.
Tyler source share