Reputation: 201
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.
Upvotes: 1
Views: 410
Reputation: 49794
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']]
Upvotes: 1
Reputation: 304
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.
Upvotes: 0
Reputation: 1252
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.
Upvotes: 1