gpt4 book ai didi

Python - append 到 pickle 列表

转载 作者:太空狗 更新时间:2023-10-29 17:57:53 24 4
gpt4 key购买 nike

我正在努力将列表 append 到 pickle 文件中。这是代码:

#saving high scores to a pickled file

import pickle

first_name = input("Please enter your name:")
score = input("Please enter your score:")

scores = []
high_scores = first_name, score
scores.append(high_scores)

file = open("high_scores.dat", "ab")
pickle.dump(scores, file)
file.close()

file = open("high_scores.dat", "rb")
scores = pickle.load(file)
print(scores)
file.close()

我第一次运行代码时,它会打印姓名和分数。

我第二次运行代码时,它打印了 2 个名字和 2 个分数。

我第三次运行代码时,它打印了名字和分数,但它用我输入的第三个名字和分数覆盖了第二个名字和分数。我只是想让它继续添加名字和分数。我不明白为什么要保存第一个名字并覆盖第二个名字。

最佳答案

如果您想写入和读取 pickled 文件,您可以为列表中的每个条目多次调用 dump。每次转储时,都会将分数 append 到 pickle 文件中,每次加载时都会读取下一个分数。

>>> import pickle as dill
>>>
>>> scores = [('joe', 1), ('bill', 2), ('betty', 100)]
>>> nscores = len(scores)
>>>
>>> with open('high.pkl', 'ab') as f:
… _ = [dill.dump(score, f) for score in scores]
...
>>>
>>> with open('high.pkl', 'ab') as f:
... dill.dump(('mary', 1000), f)
...
>>> # we added a score on the fly, so load nscores+1
>>> with open('high.pkl', 'rb') as f:
... _scores = [dill.load(f) for i in range(nscores + 1)]
...
>>> _scores
[('joe', 1), ('bill', 2), ('betty', 100), ('mary', 1000)]
>>>

您的代码失败的原因很可能是您将原始 scores 替换为未经处理的分数列表。因此,如果添加了任何新乐谱,您会把它们记在心里。

>>> scores
[('joe', 1), ('bill', 2), ('betty', 100)]
>>> f = open('high.pkl', 'wb')
>>> dill.dump(scores, f)
>>> f.close()
>>>
>>> scores.append(('mary',1000))
>>> scores
[('joe', 1), ('bill', 2), ('betty', 100), ('mary', 1000)]
>>>
>>> f = open('high.pkl', 'rb')
>>> _scores = dill.load(f)
>>> f.close()
>>> _scores
[('joe', 1), ('bill', 2), ('betty', 100)]
>>> blow away the old scores list, by pointing to _scores
>>> scores = _scores
>>> scores
[('joe', 1), ('bill', 2), ('betty', 100)]

所以它更像是 scores 的 python 名称引用问题,而不是 pickle 问题。 Pickle 只是实例化一个新列表并调用它 scores (在你的例子中),然后它垃圾收集 scores 之前指向的任何东西那个。

>>> scores = 1
>>> f = open('high.pkl', 'rb')
>>> scores = dill.load(f)
>>> f.close()
>>> scores
[('joe', 1), ('bill', 2), ('betty', 100)]

关于Python - append 到 pickle 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28077573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com