Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later?

Why not use python pickle?
Python has a great serializing module called pickle it is very easy to use.

import cPickle
cPickle.dump(obj, open('save.p', 'wb')) 
obj = cPickle.load(open('save.p', 'rb'))

There are two disadvantages with pickle:

  • It’s not secure against erroneous or
    maliciously constructed data. Never
    unpickle data received from an
    untrusted or unauthenticated source.
  • The format is not human readable.

If you are using python 2.6 there is a builtin module called json. It is as easy as pickle to use:

import json
encoded = json.dumps(obj)
obj = json.loads(encoded)

Json format is human readable and is very similar to the dictionary string representation in python. And doesn’t have any security issues like pickle. But might be slower than cPickle.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)