In python, how to make a list or dictionary persist across sessions without being overwritten immediately the code is run?

127 Views Asked by At

This is my first question on StackOverflow so please excuse any deficiencies.

I am trying to make a leaderboard for a game. It needs to add +1 to the rankings for the player that beats the game, then save the rankings to a file.

I've tried playing around lists, dictionaries, shelve, pickle, csv file, text file so far and can't figure it out.

Here's the problem: everything I can think of has the form:

  1. Save a structure to a file e.g. save a dictionary like {1: Name1: 5, 2: Name2: 4, 3: Name3: 4, 4: Name4: 2, 5: Name5: 1, } by using e.g. pickle
  2. Perform the +1 operation on the data if the player beats the game
  3. Save the structure to the file again
  4. Exit

The problem is that when the code runs again, #1 above will overwrite #3 above.

So what I really want to do is start with an existing file and then open it up as a list or dictionary and then do #2-4 above on it.

But after lots of searching I have no idea what the right way to do this is. Is it a CSV file? A dictionary in a text file? A list in a text file? Is now the right time to learn about databases?

I'm looking for a quick and light solution. Doesn't need to scale or be particularly robust, I am a noob and this is a toy programme to learn from

2

There are 2 best solutions below

0
adrianus On

When starting the program, you could first read the leaderboard file, then run the game, and in the end, save the changes.

Here's an example with JSON:

import json

# higscores.json: {"player2": 5, "player1": 3}

# read data
try:
    with open('highscores.json', 'r') as f:
        higscores = json.load(f)
except IOError:
    # highscores not existing, create new
    higscores = {"player1": 0} 

# run the game
# ...

# edit the data, if player has beaten the game
higscores['player1'] += 1

# write it back to the file
with open('highscores.json', 'w') as f:
    json.dump(higscores, f)
0
Piotrek Wilczyński On

Modify your first step so it works in this way:

  • if file exists read it
  • otherwise create it with initial data

It could look something like this:

try:
    with open(path_to_file, 'r') as f:
        # read score from file
        score = ...
except FileNotFoundError:
    with open(path_to_file, 'w') as f:
        # save initial data to file
        score = initial_data