define variables in the txt file using python

Peter Otten __peter__ at web.de
Sat Oct 8 12:58:24 EDT 2016


Xristos Xristoou wrote:

> Τη Σάββατο, 8 Οκτωβρίου 2016 - 12:25:28 π.μ. UTC+3, ο χρήστης Xristos
> Xristoou έγραψε:
>> hello
>> 
>> 
>> i have one .txt file and i want to create python script with sys.argv or
>> argparse or other package to define some variables in the txt file and i
>> take some result.
>> 
>> 
>> 
>> txt file maybe like this :
>> 
>> input number 1= %var1%
>> input number 2= %var2%
>> result = %vresult(var1-var2)%
>> 
>> how can i write a python script to update dynamic variables in the txt
>> file ? i dont want with replace i thing so arguments is the better.
> 
> thanks Mr.Peter your code look nice,i have one question,must be running
> from cmd line ?i cant to run your code in the python script ?

You said

> i have one .txt file and i want to create python script with sys.argv or
> argparse or other package to define some variables in the txt file and i
> take some result.

in your original post, so I assumed you wanted to take the arguments from 
the command line. 

Generally speaking: expect hints and code samples on this list rather than 
ready-to-use programs. If you make an effort to adapt the example script we 
will gladly help you with the parts you cannot solve yourself.

To get you started here's the gist of my previous post cast into a function:

>>> def fill_template(template, ns):
...     parts = template.split("%")
...     for i in range(1, len(parts), 2):
...         parts[i] = str(eval(parts[i], ns))
...     return "".join(parts)
... 
>>> print(fill_template("x = %var1%\ny = %var1**2%", dict(var1=22)))
x = 22
y = 484





More information about the Python-list mailing list