在我的情况下,我希望将两个单独的列表(使用pickle.dump()
)挑选到文件中,然后从单独的文件中检索这些列表,但是当使用pickle.load()
时,我一直在努力寻找一个列表结束的位置接下来就开始了,因为即使在查看文档之后我也不知道如何pickle.dump()
以及使它们易于检索的方式。
答案 0 :(得分:9)
pickle
将按照您转储它们的顺序读取它们。
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']
。要腌制任意数量的对象,或者只是让它们更容易使用,你可以将它们放在一个元组中,然后你只需要腌制一个对象。
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']