1

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

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

重新启动项目后,列表将恢复为 [1, 2, 3]。我该如何解决?

4

2 回答 2

1

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

于 2021-06-26T01:26:44.147 回答
0

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

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]))

于 2021-06-26T01:38:51.503 回答