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>There's almost certainly a better way to do this but it sounded like an interesting problem so I decided to give it a try. I defined a text file with variable names listed as such:</p>

<p><strong>newfile.txt:</strong></p>

<pre><code>x = 1
y = 2
z = 3
</code></pre>

<p>By reading one line at a type and conforming to the "var = value" input format, you can parse the text file for the correct variable then re-write the file with the new value.</p>

<pre><code>import fnmatch


var2change = "z = 17"
identifier = var2change.split('=')[0] # Get variable name

# Read file
file = open('newfile.txt', 'r')
fileLines = file.read()
fileLines = fileLines.splitlines()

for lineNum,var in enumerate(fileLines):
    if fnmatch.fnmatch(str(var),''.join([identifier,'*'])): break # Found variable to change

file.close()

file = open("newfile.txt", "w")
for ln, data in enumerate(fileLines):
    if ln == lineNum:
        lineToWrite = ''.join([var2change, '\n'])
    else:
        lineToWrite = ''.join([data, '\n'])

    file.write(lineToWrite)

file.close()
</code></pre>

<p>This will re-write the file to read:</p>

<p><strong>newfile.txt:</strong></p>

<pre><code>x = 1
y = 2
z = 17
</code></pre>

python python-2.7 parameter-passing argparse sys