2012-11-24 43 views
0

我將不勝感激任何幫助我的家庭作業 - 這是一個簡單的程序,它應該檢查文件,如果它存在,它讀取文件,並加載數據輸入到程序中,因此您可以列出分數,並添加更多分數。其假設只保留前5位的分數。寫入和從Python中的文件讀取

然後,當你關閉程序(通過選擇選項0)它應該將前5個分數寫入scores.txt文件。我想我得到了這個工作正常,我只是無法讓程序正確讀取和填充scores文件。

這裏是到目前爲止我的代碼:

scores = [] 

#Check to see if the file exists 
try: 
    file = open("scores.txt") 
    for i in range(0, 5): 
     name = file.readline() 
     score = file.readline() 
     entry = (score, name) 
     scores.append(entry) 
     scores.sort() 
     scores.reverse() 
     scores = scores[:5] 
    file.close() 
except IOError: 
    print "Sorry could not open file, please check path." 


choice = None 
while choice != "0": 

    print """ 
    High Scores 2.0 

    0 - Quit 
    1 - List Scores 
    2 - Add a Score 
    """ 


    choice = raw_input("Choice: ") 
    print "" 

    # exit 
    if choice == "0": 
     print "Good-bye." 
     file = open("scores.txt", "w+") 
     #I kinda sorta get this now... kinda... 
     for entry in scores: 
      score, name = entry 
      file.write(name) 
      file.write('\n') 
      file.write(str(score)) 
      file.write('\n') 
     file.close() 

    # display high-score table 
    elif choice == "1": 
     print "High Scores\n" 
     print "NAME\tSCORE" 
     for entry in scores: 
      score, name = entry  
      print name, "\t", score 

    # add a score 
    elif choice == "2": 
     name = raw_input("What is the player's name?: ") 
     score = int(raw_input("What score did the player get?: ")) 
     entry = (score, name) 
     scores.append(entry) 
     scores.sort() 
     scores.reverse() 
     scores = scores[:5]  # keep only top 5 scores 

    # some unknown choice 
    else: 
     print "Sorry, but", choice, "isn't a valid choice." 

raw_input("\n\nPress the enter key to exit.") 
+0

我已經重新格式化了您的文章 - 我也暫時不會編輯您的文章 - 一次只能做一件事... –

+0

謝謝。我會記住的。 –

+1

如果你以CSV格式寫出文件而不是在不同行上的每個字段,這將會容易得多。 – jdi

回答

1

你應該嘗試寫你的文件中Comma-Separated-Value (CSV)。雖然該術語使用「逗號」一詞,但格式實際上意味着任何類型的一致性字段分隔符,每條記錄都在一行上。

Python有一個csv module來幫助讀取和寫入這種格式。但我會忽略這一點,併爲您的作業目的手動進行。

讓我們假設你有一個這樣的文件:

Bob,100 
Jane,500 
Jerry,10 
Bill,5 
James,5000 
Sara,250 

我使用逗號在這裏。

f = open("scores.txt", "r") 
scores = [] 
for line in f: 
    line = line.strip() 
    if not line: 
     continue 
    name, score = line.strip().split(",") 
    scores.append((name.strip(), int(score.strip()))) 

print scores 
""" 
[('Bob', 100), 
('Jane', 500), 
('Jerry', 10), 
('Bill', 5), 
('James', 5000), 
('Sara', 250)] 
""" 

您不必在每次讀取和追加時對列表進行排序。你可以在最後做一次:

scores.sort(reverse=True, key=lambda item: item[1]) 
top5 = scores[:5] 

我知道lambda對你來說可能是新的。這是一個匿名函數。我們在這裏使用它來告訴排序函數在哪裏找到比較的關鍵。在這種情況下,我們對分數列表中的每個項目說,使用分數字段(索引1)進行比較。

+0

我不得不重做它,但它工作起來了。主要是我只需要將'scores.append(name,score)'切換到'scores.append(得分,名字)',它正在倒着看,我很困惑,哈,但是非常感謝。 –

+0

哦,好的。那麼如果你按照這個順序存儲它們,那麼你就不需要這種關鍵的lambda了。它只會使用第一個索引 – jdi

+0

也是如此;)感謝您的幫助。 –