泡菜高分然后打印

时间:2016-02-15 12:46:32

标签: python python-3.x pickle

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

在实际节目中,得分来自简单的琐事游戏。

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]

我猜我不明白一些非常基本的东西,所以我非常感谢一个内容丰富且清晰的解释。

2 个答案:

答案 0 :(得分:0)

您可以将文件读入字典:

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,但也许这会帮助其他人。

答案 1 :(得分:0)

您可以使用'wb'模式将多个pickle写入文件,如果您需要为另外一个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和/或load所有项目,那么您可以使用(我的一个包裹) )klepto,它允许您将大型pickle数据存储到文件,目录或数据库......您可以在其中无缝地访问一个条目。

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