Python - 附加到pickle列表

时间:2015-01-21 21:54:51

标签: python append pickle

我正在努力在腌制文件中附加一个列表。 这是代码:

#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()

第一次运行代码时,会打印出名称和分数。

第二次运行代码时,它会输出2个名字和2个分数。

第三次运行代码时,它会输出第一个名称和分数,但它会覆盖第二个名称并使用我输入的第三个名称和分数进行分数。我只是想让它继续添加名称和分数。我不明白为什么它保存名字并覆盖第二个名字。

4 个答案:

答案 0 :(得分:11)

如果要写入和读取pickle文件,可以为列表中的每个条目多次调用dump。每次转储时,都会在picked文件中附加一个分数,每次加载时都会读取下一个分数。

>>> import pickle as dill
>>> 
>>> scores = [('joe', 1), ('bill', 2), ('betty', 100)]
>>> nscores = len(scores)
>>> 
>>> with open('high.pkl', 'ab') as f:
…   _ = [dill.dump(score, f) for score in scores]
... 
>>> 
>>> with open('high.pkl', 'ab') as f:
...   dill.dump(('mary', 1000), f)
... 
>>> # we added a score on the fly, so load nscores+1
>>> with open('high.pkl', 'rb') as f:
...     _scores = [dill.load(f) for i in range(nscores + 1)]
... 
>>> _scores
[('joe', 1), ('bill', 2), ('betty', 100), ('mary', 1000)]
>>>

您的代码失败的原因很可能是您使用未分组的分数列表替换原始scores。因此,如果添加了任何新分数,您就会将它们留在记忆中。

>>> scores
[('joe', 1), ('bill', 2), ('betty', 100)]
>>> f = open('high.pkl', 'wb')
>>> dill.dump(scores, f)
>>> f.close()
>>> 
>>> scores.append(('mary',1000))
>>> scores
[('joe', 1), ('bill', 2), ('betty', 100), ('mary', 1000)]
>>> 
>>> f = open('high.pkl', 'rb')
>>> _scores = dill.load(f)
>>> f.close()
>>> _scores
[('joe', 1), ('bill', 2), ('betty', 100)]
>>> blow away the old scores list, by pointing to _scores
>>> scores = _scores
>>> scores
[('joe', 1), ('bill', 2), ('betty', 100)]

因此它更像scores的python名称引用问题,而不是pickle问题。 Pickle只是实例化一个新列表并将其称为scores(在您的情况下),然后垃圾收集之前指向的scores内的任何内容。

>>> scores = 1
>>> f = open('high.pkl', 'rb')
>>> scores = dill.load(f)
>>> f.close()
>>> scores
[('joe', 1), ('bill', 2), ('betty', 100)]

答案 1 :(得分:9)

您需要先将数据库中的列表(即您的pickle文件)拉出来,然后再附加到该列表中。

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)

答案 2 :(得分:0)

实际上没有回答这个问题,但是如果有人想一次添加一个项目到泡菜,你可以通过......来实现...

private void showNotification(){

            NotificationCompat.Builder myNotification = new NotificationCompat.Builder(this, "1");

            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);

            myNotification.setAutoCancel(true);
            myNotification.setDefaults(NotificationCompat.DEFAULT_ALL);
            myNotification.setWhen(20000);
            myNotification.setTicker("Ticker");
            myNotification.setContentInfo("Info");
            myNotification.setContentIntent(pendingIntent);
            myNotification.setSmallIcon(R.drawable.height);
            myNotification.setContentTitle("New notification title");
            myNotification.setContentText("Notification text");
            myNotification.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(1, myNotification.build());

}

答案 3 :(得分:0)

不使用泡菜,而是使用h5py,它也可以解决您的目的

with h5py.File('.\PreprocessedData.h5', 'a') as hf:
    hf["X_train"].resize((hf["X_train"].shape[0] + X_train_data.shape[0]), axis = 0)
    hf["X_train"][-X_train_data.shape[0]:] = X_train_data

    hf["X_test"].resize((hf["X_test"].shape[0] + X_test_data.shape[0]), axis = 0)
    hf["X_test"][-X_test_data.shape[0]:] = X_test_data


    hf["Y_train"].resize((hf["Y_train"].shape[0] + Y_train_data.shape[0]), axis = 0)
    hf["Y_train"][-Y_train_data.shape[0]:] = Y_train_data

    hf["Y_test"].resize((hf["Y_test"].shape[0] + Y_test_data.shape[0]), axis = 0)
    hf["Y_test"][-Y_test_data.shape[0]:] = Y_test_data

source