如何在一个文件中腌制多个对象? [英] How can you Pickle multiple objects in one file?

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

问题描述

就我而言,我希望将两个单独的列表(使用 pickle.dump())腌制到一个文件中,然后从单独的文件中检索它们,但是当使用 pickle.load 时() 我一直在努力寻找一个列表的结束位置和下一个列表的开始位置,因为我根本不知道如何以一种易于检索的方式 pickle.dump() 它们,即使在浏览了文档之后.

In my case, I wish to pickle (using pickle.dump()) two separate lists to a file, then retrieve these from a separate file, however when using pickle.load() I have struggled finding where one list ends and the next begins as I simply don't know how to pickle.dump() them in a manner that makes them easy to retrieve, even after looking through documentation.

推荐答案

pickle 将按照您转储它们的顺序读取它们.

pickle will read them in the same order you dumped them in.

import pickle

test1, test2 = ["One", "Two", "Three"], ["1", "2", "3"]
with open("C:/temp/test.pickle","wb") as f:
    pickle.dump(test1, f)
    pickle.dump(test2, f)
with open("C:/temp/test.pickle", "rb") as f:
    testout1 = pickle.load(f)
    testout2 = pickle.load(f)

print testout1, testout2

打印出['One', 'Two', 'Three'] ['1', '2', '3'].要pickle任意数量的对象,或者只是让它们更容易使用,您可以将它们放在一个元组中,然后只需pickle一个对象.

Prints out ['One', 'Two', 'Three'] ['1', '2', '3']. To pickle an arbitrary number of objects, or to just make them easier to work with, you can put them in a tuple, and then you only have to pickle the one object.

import pickle

test1, test2 = ["One", "Two", "Three"], ["1", "2", "3"]
saveObject = (test1, test2)
with open("C:/temp/test.pickle","wb") as f:
    pickle.dump(saveObject, f)
with open("C:/temp/test.pickle", "rb") as f:
    testout = pickle.load(f)

print testout[0], testout[1]

打印出['One', 'Two', 'Three'] ['1', '2', '3']

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

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