How can I make a python script change itself?
<p>How can I make a python script change itself?</p>

<p>To boil it down, I would like to have a python script (<code>run.py</code>)like this</p>

<pre><code>a = 0
b = 1
print a + b
# do something here such that the first line of this script reads a = 1
</code></pre>

<p>Such that the next time the script is run it would look like</p>

<pre><code>a = 1
b = 1
print a + b
# do something here such that the first line of this script reads a = 2
</code></pre>

<p>Is this in any way possible? The script might use external resources; however, everything should work by just running the one <code>run.py</code>-file.</p>

<p>EDIT:
It may not have been clear enough, but the script should update itself, not any other file. Sure, once you allow for a simple configuration file next to the script, this task is trivial.</p>

<p><strong>Answer:</strong></p>

<p>It is actually much easier than thought. @khelwood 's suggestion works just fine, opening the script and writing it's own content to it is completely unproblematic. @Gerrat's solution also works nicely. This is how I'm having it:</p>

<pre><code># -*- coding: utf-8 -*-
a = 0
b = 1
print a + b

content = []
with open(__file__,"r") as f:
    for line in f:
        content.append(line)

with open(__file__,"w") as f:
    content[1] = "a = {n}\n".format(n=b)
    content[2] = "b = {n}\n".format(n=a+b)
    for i in range(len(content)):
        f.write(content[i])
</code></pre>

<p>For an example (changing the value of <code>a</code> each time its run):</p>

<pre><code>a = 0
b = 1
print a + b

with open(__file__, 'r') as f:
    lines = f.read().split('\n')
    val = int(lines[0].split(' = ')[-1])
    new_line = 'a = {}'.format(val+1)
    new_file = '\n'.join([new_line] + lines[1:])

with open(__file__, 'w') as f:
    f.write('\n'.join([new_line] + lines[1:]))
</code></pre>

python runtime interpreter