Xandros Xandros - 4 months ago 15
Python Question

Convert a list to a string and back

I have a virtual machine which reads instructions from tuples nested within a list like so:

[(0,4738),(0,36),
(0,6376),(0,0)]


When storing this kind of machine code program, a text file is easiest, and has to be written as a string. Which is obviously quite hard to convert back.

Is there any module which can read a string into a list/store the list in a readable way?

requirements:

-Must be human readable in stored form (hence "pickle" is not suitable)

-Must be relatively easy to implement

Thanks in Advance.

Answer

JSON!

import json

with open(data_file, 'wb') as dump:
    dump.write(json.dumps(arbitrary_data))

and similarly:

source = open(data_file, 'rb').read()
data = json.loads(source)