[Tutor] string replacement puzzlement

R. A. rob@jam.rr.com
Thu, 25 Jan 2001 21:38:00 -0600


Okay, I'm stumped, and if anyone can de-stump me a bit, you'll have my
gratitude.

I'm trying to get the hang of replacing strings within a specified file,
which I've managed to do with some success.  However, my next move was
to start trying to replace multiple items within the same file in one
fell swoop.  The following example is one of my attempts to do so, and
the results were less than impressive.  In my sample file, containing a
random collection of punctuation marks, some replacement happened, but
in each case, the original symbols were left behind, and the "?"
replacement just didn't happen.  (And I know the code is a kludge, but
it looked a bit more elegant about 42 changes ago.)

I've also tried other ways, such as telling it to open and close the
files for each operation, but to no particular avail.

import string
inputfile = open('c:\windows\desktop\\inputfile.txt', 'r')
outputfile = open('c:\windows\desktop\\outputfile.txt', 'w')
outputfile.write(inputfile.read().replace("!", "exclamation point"))
inputfile.seek(0)
outputfile.write(inputfile.read().replace(".", "period"))
inputfile.seek(0)
outputfile.write(inputfile.read().replace("?", "question mark"))
inputfile.close()
outputfile.close()

I don't know of a way to use replace() with multiple replacements as
arguments, but it's what I had in mind before I started adding all this
other foolishness.

Rob
-- 
Visit the Useless Python Repository!
http://www.lowerstandard.com/python/pythonsource.html