永久更改变量

时间:2012-12-11 23:36:20

标签: python variables

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

3 个答案:

答案 0 :(得分: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!

读取数据的代码是:

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

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

答案 1 :(得分:1)

您需要将其存储在磁盘上。除非你想要真正的幻想,否则你可以使用像CSV,JSON或YAML这样的东西来简化结构化数据。

另请查看python pickle模块。

答案 2 :(得分:1)

变量有几个生命周期:

  • 如果它们位于代码块内,则它们的值仅存在于该代码块中。这包括函数,循环和条件。
  • 如果它们位于某个对象内部,则它们的值仅存在于该对象的生命周期内。
  • 如果对象被取消引用,或者您提前将代码保留,则变量的值将丢失。

如果你想特别保留某些东西的价值,你必须坚持它。 Persistence允许您将变量写入磁盘(是的,数据库在技术上是磁盘外),并在以后检索它 - 在变量的生命周期到期后,或者程序是重新启动。

您有多种方法可以选择如何保留其网页的位置 - 严格的方法是使用SQLite;一个稍微不那么重的方法是unpickle对象,或者只是写入文本文件。

相关问题