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

<p>i want to update the variables in the text file based on arguments passed to the python script</p>

<p>txt file maybe like this :</p>

<pre><code>input number 1= %var1%
input number 2= %var2%
result = %vresult(var1-var2)%
</code></pre>

<p>must var1,var2 define by the user with some input in the python script and i take result(var1-var2 for ex)</p>

<p>i can to do this easy but i dont know how to connect arguments from the python script to txt.</p>

<p>how can i write a python script to update dynamic variables in the txt file ?</p>

<p>i dont want with replace i thing so arguments is the better.</p>

<p>This is a different way using <code>regex</code> and a dictionary, and taking input using <code>sys.argv</code>:</p>

<pre><code>import sys,re
v1 = sys.argv[1]
v2 = sys.argv[2]

with open('file.txt','r') as f:
    content = f.read()

repl = {'var1':v1, 'var2':v2}

repl_pattern = re.compile(r'(' + '|'.join(repl.keys()) + r')')
final_data = repl_pattern.sub(lambda x: repl[x.group()], content)

with open('file.txt','w') as new:
    new.write(final_data)
</code></pre>

<p><strong>results:</strong></p>

<p>The file.txt initially had the following content:</p>

<pre><code>input number 1= var1
input number 2= var2
result = vresult(var1-var2)
</code></pre>

<p>and after running the above code (with: <code>sys.argv[1]=2</code> and <code>sys.argv[2]</code>=3) the file changed to:</p>

<pre><code>input number 1= 3
input number 2= 2
result = vresult(3-2)
</code></pre>

<p>If you want <code>result = 1</code> instead of <code>result = vresult(3-2)</code> then add this code:</p>

<pre><code>result = str(int(v1)-int(v2))
key3 = 'vresult('+v1+'-'+v2+')'
final_data = final_data.replace(key3,result)
</code></pre>

<p>just before the <code>with open('file.txt','w') as new:</code> ....</p>

python python-2.7 parameter-passing argparse sys