2014-03-04 153 views
1

我對Python非常陌生,我試圖實現的是醃製字典,然後使用某種形式的循環(道歉,如果我有術語不正確!)打印文件中的所有分數。通過循環取消Python字典?

我使用Python 3.3.3,這裏是我的嘗試,用戶輸入一個名字和一個首先保存到文件中的分數,然後我嘗試打印它。但是我無法打印分數。

import pickle 

# store the scores in a pickled file 
def save_scores(player, score):  

    f = open("high_score.dat", "ab") 
    d = {player:score} 
    pickle.dump(d, f) 
    f.close 

# print all the scores from the file  
def print_scores(): 

    # this is the part that I can't get to work! 
    with open("high_score.dat", "r") as f: 
     try: 
      for player, score in pickle.load(f): 
       print("Player: ", player, " scored : ", score) 
     except EOFError: 
      pass  
    f.close 

def main(): 

    player_name = input("Enter a name: ") 
    player_score = input("Enter a score: ") 

    save_scores(player = player_name, score = player_score) 
    print_scores() 


main() 

input("\nPress the Enter key to exit") 

我已經Google'd和搜索爲#1類似的問題,但我一定是使用了錯誤的術語我還沒有找到一個解決方案。

在此先感謝。

回答

2

pickle.load(f)將返回一個字典。如果迭代字典,它會生成鍵,而不是鍵值對。

要產生鍵值巴黎,使用items()方法(如果你使用Python 2.x的使用iteritems()法):

for player, score in pickle.load(f).items(): 
    print("Player: ", k, " scored : ", v) 

要獲得多個詞典了,你需要循環:

with open("high_score.dat", "r") as f: 
    try: 
     while True: 
      for player, score in pickle.load(f).items(): 
       # print("Player: ", k, " scored : ", v) # k, v - typo 
       print("Player: ", player, " scored : ", score) 
    except EOFError: 
     pass  

順便說一句,如果你使用with聲明,你不需要自己關閉文件。

# f.close # This line is not necessary. BTW, the function call is missing `()` 
+0

感謝您的全面回答!我已更新我的問題以顯示我正在使用版本3.3.3。我也更新了代碼以反映更改,但是我現在看到以下錯誤:文件「H:/Sandbox/python/save_and_print_scores.py」,第19行,print_scores 中的玩家,pickle.load(f)中的分數。 items(): TypeError:'str'不支持緩衝接口 –

+0

@IanCarpenter,可以將'high_score.dat'文件上傳到某處? – falsetru

+1

@IanCarpenter,我在代碼中發現了一個錯字。在下面的行中,'k','v'應該被替換爲:'print(「Player:」,k,「scored:」,v)'。相應地更新了答案。 – falsetru

1

pickle.load將返回你的字典({player:score}

驗證碼:

for player, score in pickle.load(f): 

將試圖解開返回值的元組。 另外,由於你忽略了這個異常,所以很難說出錯的地方。

1

我已經做了一些修復,使您的代碼在Python 2下工作(沒有Python 3可用,對不起)。幾處地方發生了變化。這裏有一些注意事項:

#!/bin/python2 
import pickle 

# store the scores in a pickled file 
def save_scores(player, score):  
    f = open("high_score.dat", "wb") # "wb" mode instead of "ab" since there is no obvious way to split pickled objects (surely you can make it, but it seems a bit hard subtask for such task) 
    d = {player:score} 
    pickle.dump(d, f) 
    f.close() # f.close is a method; to call it you should write f.close() 

# print all the scores from the file  
def print_scores(): 

    # this is the part that I can't get to work! 
    with open("high_score.dat", "rb") as f: # "rb" mode instead of "r" since if you write in binary mode than you should read in binary mode 
     try: 
      scores = pickle.load(f) 
      for player, score in scores.iteritems(): # Iterate through dict like this in Python 2 
       print("Player: ", player, " scored : ", score) # player instead of k and score instead of v variables 
     except EOFError: 
      pass  
    # f.close -- 1. close is a method so use f.close(); 2. No need to close file as it is already closed after exiting `where` expression. 

def main(): 

    player_name = raw_input("Enter a name: ") # raw_input instead of input - Python 2 vs 3 specific 
    player_score = raw_input("Enter a score: ") 

    save_scores(player = player_name, score = player_score) 
    print_scores() 


main() 

raw_input("\nPress the Enter key to exit")