How can I make a python script change itself?

后端 未结 3 670
鱼传尺愫
鱼传尺愫 2020-12-29 10:25

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          


        
3条回答
  •  有刺的猬
    2020-12-29 11:01

    Make a file a.txt that contains one character on one line:

    0
    

    Then in your script, open that file and retrieve the value, then immediately change it:

    with open('a.txt') as f:
        a = int(f.read())
    with open('a.txt', 'w') as output:
        output.write(str(a+1))
    b = 1
    print a+b
    

    On the first run of the program, a will be 0, and it will change the file to contain a 1. On subsequent runs, a will continue to be incremented by 1 each time.

提交回复
热议问题