0

In a section of a game I am creating a user enters a username. The username and user's score are saved in an object which is pickled to an external file which has the other pickled score objects in it.

I then have a button on the UI that if clicked should display the Highest scores of all players in descending order.

I load in the file into a list with the code I found here .

Highscores = []
Highscores = pickle.load(open("Highscores.txt", "rb"))

I then use a bubble sort to sort the list of objects shown below.

def bubbleSort():
    swapOccured = True
    while swapOccured == True:
        swapOccured = False
        for i in Highscores:
            if Highscores[i].score > Highscores[i + 1].score:
                hold = Highscores[i + 1]
                Highscore[i + 1] = Highscores[i]
                Highscores[i] = Highscores[i + 1]
                swapOccured = True

The error that is getting returned is

for index in Highscores:
TypeError: iteration over non-sequence

I have looked at other questions like this for example here but the error was that the program was looping through an object not looping through a list of objects. I'm pretty sure it's not the same error as the example, I think it could be with loading in a list of objects with pickle but I'm stuck.

Any help would be greatly appreciated.

Community
  • 1
  • 1
  • 2
    Defining Highscores as a list before you load the pickle doesn't change what the object is when it is loaded; it just overwrites the previous value. Clearly, whatever was saved in the pickle is not a list. – Daniel Roseman Jan 11 '17 at 21:04
  • @DanielRoseman yes. I think I am appending objects to the pickle like it was a list but it's not. This is the code I am using to dump it. `currScore = calculateScore()` `currUser = tkSimpleDialog.askstring("","Please enter a Username:")` `newHighscore = scoreEntry(currScore, currUser)` `with open("Highscores.txt", "ab") as f: pickle.dump(newHighscore, f)` – Adam Higgins Jan 11 '17 at 21:15

1 Answers1

3

Just like pickle.dump dumps a single object to the file, pickle.load loads a single object from the file. If you want a list, you will need to load them all:

with open("Highscores.txt", "rb") as score_file:
    Highscores = []
    while True:
        try:
            Highscores.append(pickle.load(score_file))
        except EOFError:
            break
zondo
  • 19,901
  • 8
  • 44
  • 83