[Tutor] Pickling

Michael P. Reilly arcege@speakeasy.net
Tue, 24 Jul 2001 18:25:48 -0400 (EDT)


Timothy M. Brauch wrote
> I read the tutorial and I thought I actually understood what was going
> on, but appearently I didn't.
> 
> I have some files whose contents are something like:
> [[1]]
> or
> [[1, 1], [2]]
> that is, lists of lists.  I would like to access this data as lists of
> lists, which is where pickle comes in.  But, I can't quite get it worked
> out.  My interpreter session is as follows.

Unpickling only works when the data in the file is already pickled.

The pickled value looks nothing like the Python representation.

>>> import pickle
>>> pickle.dumps([[1]])
'(lp0\012(lp1\012I1\012aa.'
>>> pickle.loads('(lp0\012(lp1\012I1\012aa.')
[[1]]
>>>

If you want to handle this as text in the file, then I suggest using
the eval function.

>>> line = file.readline()
'[[1]]\012'
>>> line
>>> expr = eval(line, {'__builtins__': {}})
>>> expr
[[1]]
>>> line = file.readline()
>>> line
'[[1, 1], [2]]\012'
>>> expr = eval(line, {'__builtins__': {}})
>>> expr
[[1, 1], [2]]
>>>

The "{'__builtins__': {}}" is to prevent the input from getting access
to things like the built-in functions.

Hope this has helped.

  -Arcege


-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |