How to increment variable every time script is run in Python?

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

I have a Python script that I want to increment a global variable every time it is run. Is this possible?

回答1:

Pretty easy to do with an external file, you can create a function to do that for you so you can use multiple files for multiple vars if needed, although in that case you might want to look into some sort of serialization and store everything in the same file. Here's a simple way to do it:

def get_var_value(filename="varstore.dat"):     with open(filename, "a+") as f:         val = int(f.read() or 0) + 1         f.seek(0)         f.truncate()         f.write(str(val))         return val  your_counter = get_var_value() print("This script has been run {} times.".format(your_counter))  # This script has been run 1 times # This script has been run 2 times # etc.

It will store in varstore.dat by default, but you can use get_var_value("different_store.dat") for a different counter file.



回答2:

Yes, you need to store the value into a file and load it back when the program runs again. This is called program state serialization or persistency.



回答3:

For a code example:

with open("store.txt",'r') as f: #open a file in the same folder     a = f.readlines()            #read from file to variable a #use the data read b = int(a[0])                    #get integer at first position b = b+1                          #increment with open("store.txt",'w') as f: #open same file     f.write(str(b))              #writing a assuming it has been changed

The a variable will I think be a list when using readlines.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!