Pickle Dump替换当前文件数据 [英] Pickle dump replaces current file data

查看:339
本文介绍了Pickle Dump替换当前文件数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用泡菜时,它可以正常工作,并且我可以倾倒任何负载.

When I use pickle, it works fine and I can dump any load.

问题是,如果我关闭程序并尝试再次转储,它将用新的转储替换旧的文件数据.这是我的代码:

The problem is if I close the program and try to dump again, it replaces the old file data with the new dumping. Here is my code:

import pickle
import os
import time


dictionary = dict()


def read():
    with open('test.txt', 'rb') as f:
        a = pickle.load(f)
    print(a)
    time.sleep(2)


def dump():
    chs = raw_input('name and number')
    n = chs.split()
    dictionary[n[0]] = n[1]
    with open('test.txt', 'wb') as f:
        pickle.dump(dictionary, f)


Inpt = raw_input('Option : ')
if Inpt == 'read':
    read()
else:
    dump()

推荐答案

当您以w模式(或wb)打开文件时,它会告诉该文件写入一个全新的文件,并擦除其中已经存在的所有文件

When you open a file in w mode (or wb), that tells it to write a brand-new file, erasing whatever was already there.

文档所述:

最常用的mode值是'r'表示读取,'w'表示写入(如果文件已存在则将其截断),以及'a'表示附加…

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending…

换句话说,您要使用'ab',而不是'wb'.

In other words, you want to use 'ab', not 'wb'.

但是,当您将新的转储追加到同一文件时,最终得到的文件由多个单独的值组成.如果您只调用一次load,它将仅加载第一个.如果要加载所有 ,则需要编写可实现此目的的代码.例如,您可以循环load直到EOFError.

However, when you append new dumps to the same file, you end up with a file made up of multiple separate values. If you only call load once, it's just going to load the first one. If you want to load all of them, you need to write code that does that. For example, you can load in a loop until EOFError.

确实,您要执行的操作似乎不是要添加到pickle文件中,而是要 modify 现有的腌制字典.

Really, it looks like what you're trying to do is not to append to the pickle file, but to modify the existing pickled dictionary.

您可以使用将所有转储加载并合并在一起的函数来做到这一点,如下所示:

You could do that with a function that loads and merges all of the dumps together, like this:

def Load():
    d = {}
    with open('test.txt', 'rb') as f:
        while True:
            try:
                a = pickle.load(f)
            except EOFError:
                break
            else:
                d.update(a)
    # do stuff with d

但是,随着越来越多的相同值的副本堆积起来,运行程序的时间将越来越慢.要正确,您需要加载旧字典,对其进行修改,然后转储修改后的版本.为此,您想要 w模式.

But that's going to get slower and slower the more times you run your program, as you pile on more and more copies of the same values. To do that right you need to load the old dictionary, modify that, and then dump the modified version. And for that, you want w mode.

但是,至少在键是字符串的情况下,保留字典的更好的方法是使用 dbm (如果值也是字符串)或 shelve (否则),而不是首先放在字典中.

However, a much better way to persist a dictionary, at least if the keys are strings, is to use dbm (if the values are also strings) or shelve (otherwise) instead of a dictionary in the first place.

这篇关于Pickle Dump替换当前文件数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆