私はPythonに非常に慣れていないので、他の場所でこれの修正を見逃さなかったことを願っています。購入した本の練習問題の 1 つである簡単なプログラムを持っていますが、問題が発生しています。ファイルを開いてリストに書き込むプログラムがあります。次に、ユーザーは入力でリストを更新できます。ユーザーが終了すると、最新のコンテンツでリストが更新されます。並べ替えオプションを除いて、すべて正常に機能します。ファイルからのスコアが一重引用符で囲まれて表示され、スコアはプログラムが実行されていないときに更新されます。また、それらをまったくソートしません。これを確実に行うために、さまざまな方法を試しました。これは長期的にはそれほど重要ではないと確信していますが、私はそれを理解したかったのです.
ここにコードがあります
# 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.")