Search code examples
pythonruntimeinterpreter

How can I make a python script change itself?


How can I make a python script change itself?

To boil it down, I would like to have a python script (run.py)like this

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

Such that the next time the script is run it would look like

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

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

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.


Solution

  • For an example (changing the value of a each time its run):

    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(new_file)