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

Drew Perttula drewp@bigasterisk.com
Tue Mar 4 13:33:01 2003


Danny Yoo wrote:
> 
> 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. 


Almost-- Python strings are immutable, meaning that once the read()
method created the string it returned, that string object will never
change. So, even though the string object does indeed have a replace()
method, that method can't alter the string in place: instead, it returns
a new string with the changes.

So here's the fix:

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

I changed 'file' so it's not the name of a builtin type, like someone
else suggested. And, I replaced s with the new string returned by the
replace() method. The rest of the program that writes s to a file doesn't
have to change.

-Drew