[Tutor] pickling, writing, reading individual lists from a file
Lie Ryan
lie.1296 at gmail.com
Mon Nov 3 12:53:08 CET 2008
On Mon, 03 Nov 2008 06:42:28 -0500, Kent Johnson wrote:
> 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()
Ah, I see, that's why the pickle module contains Pickler object.
btw, I have to add, none of the five code I wrote is tested at all, and
definitely #4 wouldn't work as it assumed there is a function that could
automagically escape the string. And, using Pickler object is probably
the best solution here.
More information about the Tutor
mailing list