If you did the extra credit 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:
- close -- Closes the file. Like
File->Save..
in your editor. - read -- Reads the contents of the file, you can assign the result to a variable.
- readline -- Reads just one line of a text file.
- truncate -- Empties the file, watch out if you care about the file.
- write(stuff) -- Writes stuff to the file.
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:
.. literalinclude:: ex/ex16.py :linenos:
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 5 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:
.. literalinclude:: ex/ex16.txt :language: console
Now, open up the file you made (in my case test.txt
) in your
editor and check it out. Neat right?
- If you feel you do not understand this, go back through and use the comment trick to get it squared away in your mind. One simple English comment above each line will help you understand, or at least let you know what you need to research more.
- Write a script similar to the last exercise that uses
read
andargv
to read the file you just created. - There's too much repetition in this file. Use strings, formats, and escapes
to print out
line1
,line2
, andline3
with just onetarget.write()
command instead of 6. - Find out why we had to pass a
'w'
as an extra parameter toopen
. Hint:open
tries to be safe by making you explicitly say you want to write a file. - If you open the file with
'w'
mode, then do you really need thetarget.truncate()
? Go read the docs for Python'sopen
function and see if that's true.