pickle-将多个对象放入一个文件中? [英] pickle - putting more than 1 object in a file?

查看:99
本文介绍了pickle-将多个对象放入一个文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法可以将许多腌制对象(实际上是元组)转储到文件中.

I have got a method which dumps a number of pickled objects (tuples, actually) into a file.

我不想将它们放到一个列表中,我真的想将几次转储到同一文件中. 我的问题是,如何再次加载对象? 第一个和第二个对象只有一条线长,因此可以与readlines一起使用. 但是其他所有的都更长. 自然,如果我尝试

I do not want to put them into one list, I really want to dump several times into the same file. My problem is, how do I load the objects again? The first and second object are just one line long, so this works with readlines. But all the others are longer. naturally, if I try

myob = cpickle.load(g1.readlines()[2])

其中g1是文件,我收到一个EOF错误,因为我的腌制对象长于一行. 有没有办法只拿我腌制的东西?

where g1 is the file, I get an EOF error because my pickled object is longer than one line. Is there a way to get just my pickled object?

推荐答案

如果将文件句柄直接传递给pickle,则可以获得所需的结果.

If you pass the filehandle directly into pickle you can get the result you want.

import pickle

# write a file
f = open("example", "w")
pickle.dump(["hello", "world"], f)
pickle.dump([2, 3], f)
f.close()

f = open("example", "r")
value1 = pickle.load(f)
value2 = pickle.load(f)
f.close()

pickle.dump将追加到文件的末尾,因此您可以多次调用它以写入多个值.

pickle.dump will append to the end of the file, so you can call it multiple times to write multiple values.

pickle.load将仅从文件中读取足够的数据以获取第一个值,从而使文件句柄保持打开状态并指向文件中下一个对象的开始.然后,第二个调用将读取第二个对象,并将文件指针保留在文件末尾.如您所料,第三次呼叫将失败,并显示EOFError.

pickle.load will read only enough from the file to get the first value, leaving the filehandle open and pointed at the start of the next object in the file. The second call will then read the second object, and leave the file pointer at the end of the file. A third call will fail with an EOFError as you'd expect.

尽管我在示例中使用的是普通的pickle,但该技术与cPickle的作用相同.

Although I used plain old pickle in my example, this technique works just the same with cPickle.

这篇关于pickle-将多个对象放入一个文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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