Python-附加到腌制列表
我正在努力将列表添加到腌制文件中. 这是代码:
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.
第二次运行代码时,它将打印2个名称和2个分数.
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.
您需要先从数据库(即泡菜文件)中提取列表,然后再附加到列表中.
You need to pull the list from your database (i.e. your pickle file) first before appending to it.
import pickle
import os
high_scores_filename = 'high_scores.dat'
scores = []
# first time you run this, "high_scores.dat" won't exist
# so we need to check for its existence before we load
# our "database"
if os.path.exists(high_scores_filename):
# "with" statements are very handy for opening files.
with open(high_scores_filename,'rb') as rfp:
scores = pickle.load(rfp)
# Notice that there's no "rfp.close()"
# ... the "with" clause calls close() automatically!
first_name = input("Please enter your name:")
score = input("Please enter your score:")
high_scores = first_name, score
scores.append(high_scores)
# Now we "sync" our database
with open(high_scores_filename,'wb') as wfp:
pickle.dump(scores, wfp)
# Re-load our database
with open(high_scores_filename,'rb') as rfp:
scores = pickle.load(rfp)
print(scores)