Python pickle - 在一个文件中放入 1 个以上的对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15463387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pickle - putting more than 1 object in a file?
提问by newnewbie
I have got a method which dumps a number of pickled objects (tuples, actually) into a file.
我有一种方法可以将许多腌制对象(实际上是元组)转储到一个文件中。
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
我不想把它们放在一个列表中,我真的想多次转储到同一个文件中。我的问题是,如何再次加载对象?第一个和第二个对象只有一行长,所以这适用于 readlines。但所有其他人都更长。当然,如果我尝试
myob = cpickle.load(g1.readlines()[2])
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?
其中 g1 是文件,我收到一个 EOF 错误,因为我腌制的对象比一行长。有没有办法只得到我的腌制对象?
回答by martineau
Don't try reading them back as lines of the file, justpickle.load()the number of objects you want. See my answer to the question How to save an object in Pythonfor an example of doing that.
不要尝试将它们作为文件的行读回,只是pickle.load()你想要的对象数量。请参阅我对如何在 Python 中保存对象的问题的回答,以获取执行此操作的示例。
回答by Martin Atkins
If you pass the filehandle directly into pickle you can get the result you want.
如果将文件句柄直接传递给pickle,则可以获得所需的结果。
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.dumpwill append to the end of the file, so you can call it multiple times to write multiple values.
pickle.dump将附加到文件的末尾,因此您可以多次调用它以写入多个值。
pickle.loadwill 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 EOFErroras you'd expect.
pickle.load将仅从文件中读取足以获取第一个值的内容,保持文件句柄打开并指向文件中下一个对象的开头。然后第二个调用将读取第二个对象,并将文件指针留在文件末尾。EOFError如您所料,第三次调用将失败。
Although I used plain old picklein my example, this technique works just the same with cPickle.
尽管我pickle在示例中使用了普通的 old ,但这种技术与cPickle.
回答by Samuel
I think the best way is to pack your data into a single object before you store it, and unpack it after loading it. Here's an example using
a tuple as the container(you can use dict also):
我认为最好的方法是在存储之前将数据打包到单个对象中,并在加载后将其解包。下面是一个使用元组作为容器(you can use dict also)的例子:
a = [1,2]
b = [3,4]
with open("tmp.pickle", "wb") as f:
pickle.dump((a,b), f)
with open("tmp.pickle", "rb") as f:
a,b = pickle.load(f)

