Reputation: 727
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:
Upvotes: 28
Views: 40340
Reputation: 1122022
Use the json
module:
string = json.dumps(lst)
lst = json.loads(string)
Demo:
>>> import json
>>> lst = [(0,4738),(0,36),
... (0,6376),(0,0)]
>>> string = json.dumps(lst)
>>> string
'[[0, 4738], [0, 36], [0, 6376], [0, 0]]'
>>> lst = json.loads(string)
>>> lst
[[0, 4738], [0, 36], [0, 6376], [0, 0]]
An alternative could be to use repr()
and ast.literal_eval()
; for just lists, tuples and integers that also allows you to round-trip:
>>> from ast import literal_eval
>>> string = repr(lst)
>>> string
'[[0, 4738], [0, 36], [0, 6376], [0, 0]]'
>>> lst = literal_eval(string)
>>> lst
[[0, 4738], [0, 36], [0, 6376], [0, 0]]
JSON has the added advantage that it is a standard format, with support from tools outside of Python support serialising, parsing and validation. The json
library is also a lot faster than the ast.literal_eval()
function.
Upvotes: 46
Reputation: 21914
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)
Upvotes: 21
Reputation: 251
eval
should do it in a simple way:
>>> str([(0,4738),(0,36),(0,6376),(0,0)])
'[(0, 4738), (0, 36), (0, 6376), (0, 0)]'
>>> eval(str([(0,4738),(0,36),(0,6376),(0,0)]))
[(0, 4738), (0, 36), (0, 6376), (0, 0)]
Upvotes: 20
Reputation: 6507
If you're just dealing with primitive Python types, you can just use the built-in repr()
:
Help on built-in function repr in module __builtin__:
repr(...)
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
Upvotes: 1
Reputation: 113965
with open('path/to/file', 'w') as outfile:
for tup in L:
outfile.write("%s\n" %' '.join(str(i) for i in tup))
with open('path/to/file) as infile:
L = [tuple(int(i) for i in line.strip().split()) for line in infile]
Upvotes: 0
Reputation: 500367
If these are just two-tuples, you could store them in a CVS file using the csv
module. No need for any brackets/parentheses.
Upvotes: 0
Reputation: 34493
Just use ast.literal_eval
>>> from ast import literal_eval
>>> a = literal_eval('[(1, 2)]')
>>> a
[(1, 2)]
You can convert it into a string using repr()
.
>>> repr(a)
'[(1, 2)]'
Upvotes: 27