Newbie question: string replace

Larry Bates larry.bates at websafe.com
Tue Oct 25 13:10:37 EDT 2005


usgog at yahoo.com wrote:
> I have a config file with the following contents:
> service A = {
>   params {
>     dir = "c:\test",
>     username = "test",
>     password = "test"
>   }
> }
> 
> I want to find username and replace the value with another value. I
> don't know what the username value in advance though. How to do it in
> python?
> 
I know this is not what you asked, but why not convert to a
configuration file that can be processed by ConfigParser?

[service_A]
dir=C:\test
username=test
password=test

Then you can do the following to change:

import ConfigParser
INI=ConfigParser.ConfigParser()
INI.read(r'C:\program.ini')
INI.set('service_A','username','newusername')
fp=open(r'c:\program.ini','w')
INI.write(fp)
fp.close()

Larry Bates



More information about the Python-list mailing list