[Tutor] pickling, writing, reading individual lists from a file

Dinesh B Vadhia dineshbvadhia at hotmail.com
Mon Nov 3 15:03:47 CET 2008


Just one change - pickler.load() doesn't take an argument - otherwise works perfectly!  Thank-you.

...
6. Make multiple calls to dump() and load() using an explicit pickler, pickling directly to the file (not tested):

import cPickle as pickle

filename = 'lists.txt'
fw = open(filename, 'wb')             # Note open in binary mode for protocol 2
pickler = pickle.Pickler(fw, 2)
for l in m:
    pickler.dump(l)
fw.close()

fr = open(filename, 'rb')
pickler = pickle.Unpickler(fr)
for i in range(3):
    line = pickler.load()
    print line
fr.close()
...

Dinesh


--------------------------------------------------------------------------------
From: Kent Johnson <kent37 <at> tds.net>
Subject: Re: pickling, writing, reading individual lists from a file
Newsgroups: gmane.comp.python.tutor
Date: 2008-11-03 11:42:28 GMT (2 hours and 16 minutes ago)

On Mon, Nov 3, 2008 at 6:15 AM, Lie Ryan <lie.1296 <at> gmail.com> wrote:
> On Sun, 02 Nov 2008 23:20:47 -0800, Dinesh B Vadhia wrote:
>
>> I want to pickle a bunch of lists and write each list separately to a
>> fileand then read them back.

> To solve your problem, you have several alternative possibilities:

6. Make multiple calls to dump() and load() using an explicit pickler,
pickling directly to the file (not tested):

filename = 'lists.txt'
fw = open(filename, 'wb') # Note open in binary mode for protocol 2
pickler = pickle.Pickler(fw, 2)
for l in m:
        pickler.dump(l)
fw.close()

fr = open(filename, 'rb')
pickler = pickle.Unpickler(fr)
for i in range(3):
        line = pickler.load(fr)
        print line
fr.close()

Kent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081103/60e94c19/attachment.htm>


More information about the Tutor mailing list