问题描述
我需要附加到一个pickle文件中(因为我没有一次性带上整个字典).所以为了做同样的事情,我编写了以下代码:
导入泡菜p={}p[1]=2q={}q['a']=pp={}p[2]=0pickle.dump(q, open("save12.p","ab"))f={}f['b']=ppickle.dump(f,open("save12.p","ab"))
但是,当我加载泡菜文件时,我在那里找不到字典 f 的值??????
有人可以建议我应该如何添加泡菜文件吗???
像dbm"这样的数据库也不能满足我的需要,因为我在 Windows 上工作
Pickle 流是完全独立的,因此 unpickling 将一次 unpickle 一个对象.
因此,要对多个流进行 unpickle,您应该反复对文件进行 unpickle,直到出现 EOFError:
>>>f=open('a.p', 'wb')>>>pickle.dump({1:2}, f)>>>pickle.dump({3:4}, f)>>>f.close()>>>>>>f=open('a.p', 'rb')>>>pickle.load(f){1:2}>>>pickle.load(f){3:4}>>>pickle.load(f)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中EOF错误所以你的 unpickle 代码可能看起来像
进口泡菜对象 = []而 1:尝试:objs.append(pickle.load(f))除了EOFError:休息
i need to append to a pickle file (as i don't have the entire dictionary with me at one go). So for doing the same I have written the following code:
import pickle
p={}
p[1]=2
q={}
q['a']=p
p={}
p[2]=0
pickle.dump(q, open("save12.p","ab"))
f={}
f['b']=p
pickle.dump(f,open("save12.p","ab"))
However, when I am loading the pickle file I don't find the value of dictionary f there?????
Can someone please suggest as to how should I go about appending in a pickle file???
Also databases like 'dbm' are not working for my need as i am working on windows
Pickle streams are entirely self-contained, and so unpickling will unpickle one object at a time.
Therefore, to unpickle multiple streams, you should repeatedly unpickle the file until you get an EOFError:
>>> f=open('a.p', 'wb')
>>> pickle.dump({1:2}, f)
>>> pickle.dump({3:4}, f)
>>> f.close()
>>>
>>> f=open('a.p', 'rb')
>>> pickle.load(f)
{1: 2}
>>> pickle.load(f)
{3: 4}
>>> pickle.load(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
EOFError
so your unpickle code might look like
import pickle
objs = []
while 1:
try:
objs.append(pickle.load(f))
except EOFError:
break
这篇关于如何在python中使用pickle附加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!