I am very new to python, and I am hoping I didnt miss a fix for this somewhere else. I have a simple program that was one of the practice excercises in a book I purchased and I am running into an issue. I have a program that opens a file and writes it to a list. Then a user can update the list with input, and when a user exits it updates the list with the latest content. Everything works fine except the sort option. It shows the scores from the file with a single quote infront of them, and the scores updated while the program was running without. It also doesn’t sort them at all. I have tried many different way to do this without fail. I am sure this is not that important in the long run, but I wanted to figure it out.
Here is the code
# 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.")
When you add scores from the file, you’re adding them as strings:
scores.append(line.rstrip("\n")). But when you add scores during the program, you’re adding them as integers:int(raw_input("What score did you get?: ")).When Python sorts a list containing both strings and integers, it’ll sort the strings according to character order (so
'1' < '12' < '3'), and sort the integers separately, putting the integers before the strings:Presumably it’s printing out a single quote after the characters as well as before, as it does here (indicating that it’s a string).
So, when you’re reading the file at the start, turn them into an integer just like you do when you read user input.
Some other tips:
scores.sort(reverse=True)will sort in reverse order without having to go through the list twice.except:: that’ll catch absolutely any problem with the program, including the user hitting^Cto try to quit, the system running out of memory, etc. You should doexcept Exception:as a catch-all to get exceptions that it’s possible to recover from but not those kinds of system errors, or a more specific exception when you want to handle only certain types.