[Tutor] Editing files through Python

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Sep 1 23:48:58 CEST 2004


> I've been playing around with the advice you was sent me
> and have become a little confused about the ideas of the
> input_file (r) and the output_file (w).  Can they be the
> same file?

No. Actually what's being suggested is what Microsoft Word
(and almost all other programs) do. They copy the original
file(foo.doc) to a temp file (~foo.doc) and open the temporary
copy and read it. When you do a save they overwrite the
original file and rename ~foo.doc to foo.bak.

Or some similar sequence, basically they create a new file
so that they don't corrupt the original until an explicit
save is done. It just looks like to the user as if it is
opening and modifying the original file, in fact it is
making copies and operating on two different files.
(actually 3 if you include an auto-save recovery version!)

> Do I have to close the input file before writing to the
> output file?

Not if you use the model above - ie operate on a copy of
the original and don't overwrite it until you are ready.

> Here is the program I wrote following your example,
> and an error that always appears, relating to the input file,
> that is perplexing me.

This bit has been answered already :-)

> IOError: [Errno 2] No such file or directory:
'C:\\BryFolder\\kt.1.24.data.036rd.test.dat'

Alan G.



More information about the Tutor mailing list