If you did the Study Drills from the last exercise you should have seen all sorts of commands (methods/functions) you can give to files. Here's the list of commands I want you to remember:
For now these are the important commands you need to know. Some of them take parameters, but we do not really care about that. You only need to remember that write takes a parameter of a string you want to write to the file.
Let's use some of this to make a simple little text editor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
from sys import argv script, filename = argv print "We're going to erase %r." % 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." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "I'm going to write these to the file." target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print "And finally, we close it." target.close()
That's a large file, probably the largest you have typed in. So go slow, do your checks, and make it run. One trick is to get bits of it running at a time. Get lines 1-8 running, then five more, then a few more, etc., until it's all done and running.
There are actually two things you will see. First the output of your new script:
$ python ex16.py test.txt We're going to erase 'test.txt'. If you don't want that, hit CTRL-C (^C). If you do want that, hit RETURN. ? Opening the file... Truncating the file. Goodbye! Now I'm going to ask you for three lines. line 1: Mary had a little lamb line 2: It's fleece was white as snow line 3: It was also tasty I'm going to write these to the file. And finally, we close it.
Now, open up the file you made (in my case test.txt) in your editor and check it out. Neat, right?