[Tutor] newbie question--saving changes to a file

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue Mar 4 12:00:13 2003


On Tue, 4 Mar 2003, Ron Nixon wrote:

> How do I save the changes I make to a file say for example if I change
> old to new in a file and then want to save the new changes to another
> file?
>
> import string
>
> file = open('c:/file.txt')
>
> s = file.read()
>
> s.replace('old', 'new')
>
> Please excuse the questions if it sounds to basic, but I have not be
> able to find an example of how to do this in the documentation--or
> perhaps I simply didn't see it.


Hi Ron,

No problem; your question is perfectly reasonable!  By the end of your
program:

###
import string
file = open('c:/file.txt')
s = file.read()
s.replace('old', 'new')
###

we have, in our computer's memory, the contents of that file, with some
modifications that we'd like to save back to disk.  What we can do is open
up the same file in "write" mode:

###
out_file = open("c:/file.txt", "w")
###

This clears out the file so that it's ready for us to start writing into
it.  Once we have an open file, we can write() to it:

###
out_file.write(s)
###

Finally, we should close() the file.  Python can put some finishing
touches (like flushing buffers) when we close a file, so that we're sure
that every last drop of data has gone into our out_file:

###
out_file.close()
###



Altogether, the program might look like this:

###
import string
file = open('c:/file.txt')
s = file.read()
s.replace('old', 'new')
out_file = open("c:/file.txt", "w")
out_file.write(s)
out_file.close()
###

And this should work, if I haven't put in any typos.  *grin*


But some people might feel slightly uncomfortable about how open() will
clear out a file when it's in write mode.  What happens if the power goes
out before we have a chance to write() the modified contents?  Think Ellen
Feiss.

A word processor, like Microsoft Word or Emacs, should be careful to avoid
this danger.  What these programs do (or should do) is make a copy of the
old file --- a backup --- into a separate file.  Once we have a backup,
then we can go ahead and write into our file with some security: even if
power goes out, we have a good chance of just retrieving our backup.

Hope this helps!