Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Sequential Object Store

6 views
Skip to first unread message

GZ

unread,
Aug 7, 2010, 12:26:39 PM8/7/10
to
Hi All,

I need to store a large number of large objects to file and then
access them sequentially. I am talking about a few thousands of
objects and each with size of a few hundred kilobytes, and total file
size a few gigabytes. I tried shelve, but it is not good at
sequentially accessing the data. In essence, shelve.keys() takes
forever.

I am wondering if there is a module that can persist a stream of
objects without having to load everything into memory. (For this
reason, I think Pickle is out, too, because it needs everything to be
in memory.)

Thanks,
GZ

Alex Willmer

unread,
Aug 7, 2010, 7:54:03 PM8/7/10
to
On Aug 7, 5:26 pm, GZ <zyzhu2...@gmail.com> wrote:
> I am wondering if there is a module that can persist a stream of
> objects without having to load everything into memory. (For this
> reason, I think Pickle is out, too, because it needs everything to be
> in memory.)

From the pickle docs it looks like you could do something like:

try:
import cPickle as pickle
except ImportError
import pickle

file_obj = open('whatever', 'wb')
p = pickle.Pickler(file_obj)

for x in stream_of_objects:
p.dump(x)
p.memo.clear()

del p
file_obj.close()

then later

file_obj = open('whatever', 'rb')
p = pickle.Unpickler(file_obj)

while True:
try:
x = p.load()
do_something_with(x)
except EOFError:
break

Your loading loop could be wrapped in a generator function, so only
one object should be held in memory at once.

GZ

unread,
Aug 9, 2010, 3:39:29 PM8/9/10
to
Hi Alex,

This totally works!

Thanks!

0 new messages