1

I am creating a leader board for my game in python and I want it to save it so that I can retrieve it next time I open up the game.

Leader_board  = []
Temp_Leader_board = []

PlayerName = str(No1+No2+No3+No4+No5+No6+No7+No8)
Array = [str(Deaths),PlayerName]
Temp_Leader_board.append(Array)
Leader_board = sorted(Temp_Leader_board, key=lambda player: player[0])

The last line is to order the score from smallest to largest.

2
  • You have two main options. You could store each element in your list in a custom format. Or you could use pickle to serialize your list into a file. Commented Apr 19, 2017 at 16:14
  • BTW, we call them lists in python, not arrays. Commented Apr 19, 2017 at 16:44

4 Answers 4

1

As @matusko and @Christian Dean stated, what you are looking for is serialization, which Python has a built-in module for called pickle. Personally, since this seems like a simpler serialization usecase, I'd suggest going for cPickle, which does the same thing as pickle but is way faster because it's written in C. See here for a guide on how to use them for serializing different kinds of data.

Sign up to request clarification or add additional context in comments.

Comments

1

My preferred solution for simple serialization is yaml. It has the advantage of being human readable, but has the disadvantage of only being able to serialize simple data structures. It looks like it would work fine in this case:

Test Code:

leader_board = [
    [30, 'Player A'],
    [10, 'Player B'],
]

import yaml

# save the leader board
with open('LeaderBoard.yml', 'w') as f:
    f.write(yaml.dump(leader_board))

# read the leader board from yaml file
with open('LeaderBoard.yml', 'r') as f:
    read_leader_board = yaml.load(f.read())

# show yaml format and restored data
print(yaml.dump(leader_board))
print(read_leader_board )

Results:

- [30, Player A]
- [10, Player B]

[[30, 'Player A'], [10, 'Player B']]

Comments

0

The simplest way would be using a pickle

Comments

0

Sounds like you are looking for a way to serialize your list so that it can be saved to a file and then read back in later. For serializing python objects, you can use the python module pickle (reference page). For info on writing and reading from files, check out here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.