永久更改变量

Mal*_*lyG 6 python variables

我正在写一个小程序,可以帮助您跟踪书中的页面.我不喜欢书签,所以我想"如果我可以创建一个可以接受用户输入的程序,然后显示他们编写的文本的数量或字符串,在这种情况下将是他们的页码,该怎么办?"重新开始,让他们随时改变它?" 它只需要几行代码,但问题是,如何在下次打开程序时显示相同的数字?变量会重置,不是吗?有没有办法以这种方式永久改变变量?

Dea*_*hex 5

您可以将值存储在文件中,然后在启动时加载它们.

代码看起来有点像这样

variable1 = "fi" #start the variable, they can come from the main program instead
variable2 = 2

datatowrite = str(variable1) + "\n" + str(variable2) #converts all the variables to string and packs them together broken apart by a new line

f = file("/file.txt",'w')
f.write(datatowrite) #Writes the packed variable to the file
f.close() #Closes the file !IMPORTANT TO DO!
Run Code Online (Sandbox Code Playgroud)

读取数据的守则是:

import string

f = file("/file.txt",'r') #Opens the file
data = f.read() #reads the file into data
if not len(data) > 4: #Checks if anything is in the file, if not creates the variables (doesn't have to be four)

    variable1 = "fi"
    variable2 = 2
else:
    data = string.split(data,"\n") #Splits up the data in the file with the new line and removes the new line
    variable1 = data[0] #the first part of the split
    variable2 = int(data[1]) #Converts second part of strip to the type needed
Run Code Online (Sandbox Code Playgroud)

请记住,使用此方法,变量文件与应用程序一起存储在明文中.任何用户都可以编辑变量并更改程序行为