【问题标题】:How do I make my project remember a variable/list after it restarts?如何让我的项目在重新启动后记住变量/列表?
【发布时间】:2021-06-26 01:23:53
【问题描述】:

我的项目要求它记住用户更新列表。问题是每次 python 项目重新启动时,更新的列表都会随之重置。这是一个例子:

list = [1, 2, 3]
list.append(4)
#the list is now [1, 2, 3, 4]

一旦我重新启动项目,列表将恢复为 [1, 2, 3]。我该如何解决这个问题?

【问题讨论】:

  • 使用文本文件,保存到您的计算机
  • 有没有办法将它保存到项目而不是文本文件?也许是一个 python 包?
  • 我不确定是否有办法,除非您想像在线数据库一样使用,例如sql ?

标签: python list memory


【解决方案1】:

要保存变量,您可以使用将存储在您的 PC 中的文本文件或 sqlite3 数据库。如果你喜欢,你也可以使用JSON文件,这样会更容易使用。

【讨论】:

    【解决方案2】:

    不是最好的,但值得一试。

    list1=[1, 2, 3]
    list1.append(4)
    with open(__file__,"r") as file:
        file1=file.readlines()
        x=globals()['list1']
        file1[0]="list1="+str(x)+str("\n")
    with open(__file__,"r+") as file2:
    
        file2.write(''.join([str(y) for y in file1]))
    
    

    【讨论】:

      猜你喜欢
      • 2020-08-26
      • 2019-03-22
      • 2019-08-04
      • 2013-09-14
      • 2015-10-20
      • 2016-08-06
      • 2014-11-13
      • 2020-02-19
      • 2021-08-05
      相关资源
      最近更新 更多