以相反的顺序打开

时间:2016-03-22 00:17:41

标签: python pickle

有没有办法反向拆卸多个物体,以便从最后一个被腌制的物品中加载腌制物品?

例如:

import pickle
a = 'string1'
b = 'string2'
with open('test', 'wb') as f:
    pickle(a, f)
    pickle(b, f)

打开并打印每个unpickling后,我希望看到:' string2',' string1'。

1 个答案:

答案 0 :(得分:2)

同时使用pickledbm。此代码适用于python2和python3(在Raspbian linux上测试)

import pickle
import dbm

OBJECTS = (
  'string1',
  'string2',
)

def store():
  db = dbm.open('test','c')
  index = 0
  for ob in OBJECTS:
    db[str(index)] =    pickle.dumps(ob)
    index += 1
  db['N'] = str(index)   # store object count
  db.close()

def load():
  db = dbm.open('test','r')
  nb = int(db['N']) 
  while nb>0:
    nb -= 1
    ob = pickle.loads(db[str(nb)])
    print (ob)
  db.close()

store()
load()

Key' N'告诉我们存储了多少个对象。这适用于大量对象。

<强>被修改

这不仅限于字符串,它也适用于pickle可以序列化的任何对象。例如,您可以写

OBJECTS = (
  ( 'A', 'b', '123' ),
  'SomeString', 
  {1: 'ABC', 2:((1,2),(3,4)), 3: [9,8,7,6]}, 
  [[],[1],[2,3],[4,5,6]],   
)