6

我正在编写一个小程序,可以帮助您跟踪您在书中的哪一页。我不喜欢书签,所以我想“如果我可以创建一个程序来接受用户输入,然后显示他们写的文本的数量或字符串,在这种情况下就是他们的页码”重新启动,并允许他们在需要时进行更改?” 只需要几行代码,但问题是,我怎样才能让它在下次打开程序时显示相同的数字?变量会重置,不是吗?有没有办法以这种方式永久更改变量?

4

3 回答 3

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

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

于 2012-12-12T00:00:12.983 回答
1

You need to store it on disk. Unless you want to be really fancy, you can just use something like CSV, JSON, or YAML to make structured data easier.

Also check out the python pickle module.

于 2012-12-11T23:55:17.160 回答
1

变量有几个生命周期:

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

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

你有几个选项来决定如何保持他们页面的位置——一个强硬的方法是使用SQLite;一个稍微不那么笨拙的方法是解开对象,或者简单地写入文本文件。

于 2012-12-12T00:08:53.823 回答