Newbie question: string replace

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Oct 25 13:14:55 EDT 2005


On Tue, 25 Oct 2005 09:37:09 -0700, 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?


Your config file looks like a cut-down mutated version of XML. Maybe you
should use real XML and the tools for working with it?

Or perhaps you should use module ConfigParser? Despite the temptation to
reinvent the wheel, it is rarely a good idea.

If you have already read the config file into a nested dictionary, then
all you need to do is:

py> service_A = ReadConfigFile()  # you must write this function
py> print service_A["params"]
{'dir': 'c:\test', 'username': 'test', 'password': 'test'}
py> service_A['params']['username'] = 'J. Random User'
py> WriteConfigFile(service_A)


Or if you insist on treating the config file as a string, try something
like this:

py> s = open('filename', 'r').read()
py> print s
service A = {
  params {
    dir = "c:\test",
    username = "test",
    password = "test"
  }
}
py> target = 'username = '
py> p1 = s.find(target) + len(target)
py> p2 = s.find(',\n', p1)
py> s = s[:p1] '"J. Random User"' + s[p2:]

That's not good enough for professional code, but it will get you started.


-- 
Steven.




More information about the Python-list mailing list