Use pickle
and dbm
together. This code works on python2 and python3 (tested on 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' tells how many objects are stored. This should work for a very large number of objects.
Edited
This is not restricted to strings, it will also work with any object that pickle
can serialize. For example, you can write
OBJECTS = (
( 'A', 'b', '123' ),
'SomeString',
{1: 'ABC', 2:((1,2),(3,4)), 3: [9,8,7,6]},
[[],[1],[2,3],[4,5,6]],
)