Home > OS >  How would I change a pickle value for highscore?(python)
How would I change a pickle value for highscore?(python)

Time:12-24

I am making a game in python and I want to add a system that saves the users highscore, and loads it the next time the application is run. To do this I am using pickle. I have been able to save the data, but I do not know how to edit the value stored in the pickle file. Code(to show what I want to do):

import pickle
hs=0
savedhs=pickle.dumps(hs)
highscore=pickle.loads(savedhs)
hs=hs 1
print(highscore)
#Expected output: 1
#output:0

How would I make it so that whenever the value of hs changes, the pickled file also changes?

CodePudding user response:

To update the pickled file, you could open it in write mode and update the value. Like this

import pickle

# Open the file in write mode
with open("highscore.pickle", "wb") as f:
    # Load the data from the file
    highscore = pickle.load(f)
    # Update the value of highscore
    highscore  = 1
    # Write the updated value back to the file
    pickle.dump(highscore, f)

  • Related