本文介绍了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.

推荐答案

您需要先从您的数据库(即您的 pickle 文件)中提取列表,然后再附加到它.

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)

这篇关于Python - 附加到腌制列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:47