我对 python 很陌生,我希望我没有错过其他地方的修复。我有一个简单的程序,它是我购买的书中的练习之一,但我遇到了一个问题。我有一个程序可以打开文件并将其写入列表。然后用户可以使用输入更新列表,当用户退出时,它会使用最新内容更新列表。除排序选项外,一切正常。它显示文件中的分数,前面有一个单引号,并且在程序没有运行时更新分数。它也根本不对它们进行排序。我尝试了许多不同的方法来做到这一点。我确信从长远来看这并不重要,但我想弄清楚。
这是代码
# High Scores
# Demonstrates list methods
scores = []
try:
text_file = open("scores.txt", "r")
for line in text_file:
scores.append(line.rstrip("\n"))
text_file.close()
except:
raw_input("Please verify that scores.txt is placed in the correct location and run again")
choice = None
while choice != "0":
print \
"""
High Scores Keeper
0 - Exit
1 - Show Scores
2 - Add a Score
3 - Delete a Score
4 - Sort Scores
"""
choice = raw_input("Choice: ")
print
# exit
if choice == "0":
try:
output_file = open("scores.txt" , "w")
for i in scores:
output_file.write(str(i))
output_file.write("\n")
output_file.close()
print "Good-bye"
except:
print "Good-bye.error"
# list high-score table
elif choice == "1":
print "High Scores"
for score in scores:
print score
# add a score
elif choice == "2":
score = int(raw_input("What score did you get?: "))
scores.append(score)
# delete a score
elif choice == "3":
score = int(raw_input("Delete which score?: "))
if score in scores:
scores.remove(score)
else:
print score, "isn't in the high scores list."
# sort scores
elif choice == "4":
scores.sort()
scores.reverse()
print scores
# some unknown choice
else:
print "Sorry, but", choice, "isn't a valid choice."
raw_input("\n\nPress the enter key to exit.")