泡菜高分然后打印

Pickle high scores and then print

我正在尝试挑选高分然后打印出来。

在实际程序中,分数是通过一个简单的问答游戏获得的。

score = 10
name = input("Name: ")
scores = [name, score]
high_scores = open("high_scores.dat", "ab")
pickle.dump(scores, high_scores)
high_scores.close()

high_scoresR = open("high_scores.dat", "rb")
results = pickle.load(high_scoresR)
print(results)
high_scores.close()

该程序只打印输入的第一个高分,无论我尝试向其转储多少分数都没有关系。示例:

['Jason', 10]

我猜我不太了解一些非常基本的东西,所以我非常感谢您提供内容丰富且清晰的解释。

您可以将您的文件读入字典:

name = input('Enter name: ')
score = input('Enter score: ')

# write new entry to file
with open('highscores.txt', 'a') as f:
    f.write(name + ':' + score + '\n')

# read file into dict
with open('highscores.txt', 'r') as f:
    lines = f.read().splitlines()
scores = dict(line.split(':') for line in lines)

for key, value in scores.items():
    print(key, value)

我不知道你在努力学习 pickle,但也许这对其他人有帮助。

您可以使用 'wb' 模式将多个泡菜写入一个文件,如果您需要重新打开它以增加一个或多个 dump,那么您应该使用追加模式 ('a',而不是 'w')。这里我使用 'wb' 写入多个条目,然后使用 'ab'.

添加一个条目
>>> scores = dict(Travis=100, Polly=125, Guido=69)
>>> import pickle                               
>>> with open('scores.pkl', 'wb') as highscores:
...   for name,score in scores.items(): 
...     pickle.dump((name,score)), highscores)
... 
>>> with open('scores.pkl', 'ab') as highscores:
...   pickle.dump(scores, highscores)
... 
>>> with open('scores.pkl', 'rb') as highscores:
...   a = pickle.load(highscores)
...   b = pickle.load(highscores)
...   c = pickle.load(highscores)
...   d = pickle.load(highscores)
... 
>>> a
('Travis', 100)
>>> b
('Polly', 125)
>>> c
('Guido', 69)
>>> d
{'Polly': 125, 'Travis': 100, 'Guido': 69}
>>> 

而且如果你有很多数据,以至于你担心无法一次 dump and/or load 所有项目,那么你可以使用 (我的软件包之一)klepto,它使您能够将大量腌制数据存储到文件、目录或数据库中……您可以一次无缝地访问一个条目。

>>> import klepto
>>> store = klepto.archives.dir_archive('high', serialized=True) 
>>> store.update(scores)
>>> store
dir_archive('high', {'Polly': 125, 'Guido': 69, 'Travis': 100}, cached=True)
>>> # dump all entries at once
>>> store.dump()
>>> # create a new empty archive proxy
>>> store2 = klepto.archives.dir_archive('high', serialized=True)
>>> store2 
dir_archive('high', {}, cached=True)
>>> # load one entry, as opposed to loading all entries
>>> store2.load('Guido')
>>> store2
dir_archive('high', {'Guido': 69}, cached=True)
>>> store2['Guido']
69
>>> # load everything else
>>> store2.load()
>>> store2
dir_archive('high', {'Polly': 125, 'Guido': 69, 'Travis': 100}, cached=True)
>>>