Generate config file from template using Python search and replace.

MRAB python at mrabarnett.plus.com
Sun Nov 29 22:23:34 EST 2015


On 2015-11-30 02:40, Rob Hills wrote:
> A program I am writing at present does exactly this and I simply do
> multiple calls to string.replace (see below)
>
> On 30/11/15 10:31, Mr Zaug wrote:
>> I seem to be heading in this direction.
>>
>> #!/usr/bin/env python
>> import re
>> from os.path import exists
>>
>> script, template_file = argv
>> print "Opening the template file..."
>>
>> with open (template_file, "r") as a_string:
>>     data=a_string.read().replace('BRAND', 'Fluxotine')
>
>          data=data.replace('STRING_2', 'New String 2')
>          data=data.replace('STRING_3', 'New String 3')
>
>> print(data)
>>
>> So now the challenge is to use the read().replace magic for multiple values.
>
> It's crude, but it works well for me!
>
You do need to watch out for matches that are part of something else.

For example, if you had this:

     template = "REPLACE_THIS but DONT_REPLACE_THIS"

and you did:

     result = template.replace("REPLACE_THIS", "Python")

you would get:

     "Python but DONT_Python"




More information about the Python-list mailing list