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

Kent Johnson kent37 at tds.net
Mon Nov 3 12:42:28 CET 2008


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


More information about the Tutor mailing list