先腌高分,然后普林

2024-10-02 18:19:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把高分腌出来然后打印出来。在

在实际程序中,分数是从一个简单的琐事游戏中获得的。在

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

程序只打印输入的第一个高分,不管我尝试向它转储多少分数。示例:

^{pr2}$

我猜我不懂一些基本的东西,所以我非常希望你能给我一个信息丰富、清晰的解释。在


Tags: name程序游戏closeopenresults分数pickle
2条回答

您可以将文件读入词典:

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'模式将多个pickle写入一个文件,如果您需要重新打开它以获得更多的dump,那么您应该使用append模式('a',而不是{})。在这里,我使用'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和/或load所有的项目,那么您可以使用(我的一个包)klepto,这使您能够将大的pickled数据存储到文件、目录或数据库中……在那里您可以一次无缝地访问一个条目。在

^{pr2}$

相关问题 更多 >