multiple replacements

siva1311 at my-deja.com siva1311 at my-deja.com
Tue Jun 27 08:47:22 EDT 2000


Hi,
I am a newbie Python programmer and was wondering the best way to make
multiple replacements of text strings in a file. I have 10-15 strings to
replace and right now I am doing this like:

  source = open(source_file,'r')
  contents = source.read()
  source.close()

  contents1 = string.replace(contents, 'foo1', 'bar1')
  contents2 = string.replace(contents1, 'foo2', 'bar2')
  ...
  contents10 = string.replace(contents9, 'foo10', 'bar10')

  dest = open(dest_file, 'w')
  dest.write(contents10)
  dest.close()

I know this must be a terrible kludge.

Using sed I can use a single statement to carry out the replacements:
    sed "s/foo1/bar1/g
         s/foo2/bar2/g
         ...
         s/foo10/bar10/g" source_file > dest_file

so I assume there must be a much better method than I am currently using
in my Python version.

Any suggestions for improvement to the Python code are appreciated.

-Brad


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list