我將不勝感激任何幫助我的家庭作業 - 這是一個簡單的程序,它應該檢查文件,如果它存在,它讀取文件,並加載數據輸入到程序中,因此您可以列出分數,並添加更多分數。其假設只保留前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.")
我已經重新格式化了您的文章 - 我也暫時不會編輯您的文章 - 一次只能做一件事... –
謝謝。我會記住的。 –
如果你以CSV格式寫出文件而不是在不同行上的每個字段,這將會容易得多。 – jdi