Python: replace a string by a float in txt file
Question: Here is a problem.

I have a .py file and a .txt. To simplify, my .txt looks like:

    
    
    @x@
    

In the .py I have

    
    
    x=15
    

I would like to replace @x@ in the txt by the value saved in the py, ie my txt
should look like

    
    
    15
    

I tried with this:

    
    
    for i, line in enumerate(fileinput.input('mytxtfile.txt', inplace = 1)):
        sys.stdout.write(line.replace('@x@', 'x'))
    

or with

    
    
    for i, line in enumerate(fileinput.input('mytxtfile.txt', inplace = 1)):
        sys.stdout.write(line.replace('@x@', 'str(x)'))
    

The problem is that the "replace" method seems to consider only strings and I
need to evaluate the value of the string. Any idea how to do it?

Thanks


Answer: The `string.Template` class is a good way to do this.

<http://docs.python.org/library/string.html#template-strings>

    
    
    from string import Template
    class MyTemplate( Template ): 
        delimiter= '@'
        pattern= r"@(?P<escaped>@)|@(?P<named>[_a-z][_a-z0-9]*)@|@(?P<braced>[_a-z][_a-z0-9]*)@|@(?P<invalid>)"
    

Given this class definition, you can now do this

    
    
    with open( 'a.txt', 'r' ) as source:
        t = MyTemplate(source.read())
        result= t.substitute( x=15 )
        print result
    

This allows you to use any number of substitutions anywhere in the template of
almost any complexity. This handles a very, very large number of cases
gracefully.

