I'm struggling to append a list in a pickled file. This is the code:
#saving high scores to a pickled file
import pickle
first_name = input("Please enter your name:")
score = input("Please enter your score:")
scores = []
high_scores = first_name, score
scores.append(high_scores)
file = open("high_scores.dat", "ab")
pickle.dump(scores, file)
file.close()
file = open("high_scores.dat", "rb")
scores = pickle.load(file)
print(scores)
file.close()
The first time I run the code, it prints the name and score.
The second time I run the code, it prints the 2 names and 2 scores.
The third time I run the code, it prints the first name and score, but it overwrites the second name and score with the third name and score I entered. I just want it to keep adding the names and scores. I don't understand why it is saving the first name and overwriting the second one.
Don't use pickle but use h5py which also solves your purpose
source
You need to pull the list from your database (i.e. your pickle file) first before appending to it.
If you want to write and read to the pickled file, you can call dump multiple times for each entry in your list. Each time you dump, you append a score to the pickled file, and each time you load you read the next score.
The reason your code was failing most likely is that you are replacing the original
scores
with the unpickled list of scores. So if there were any new scores added, you'd blow them away in memory.So it's more of a python name reference issue for
scores
, than it is apickle
issue.Pickle
is just instantiating a new list and calling itscores
(in your case), and then it garbage collects whatever thingscores
was pointed to before that.Doesnt actually answer the question, but if anyone would like to add a single item at a time to a pickle, you can do it by...