1

I'd like to read and write a list of lists of tuples from and to files.

g_faces = [[(3,2)(3,5)],[(2,4)(1,3)(1,3)],[(1,2),(3,4),(6,7)]]

I used

  • pickle.dump(g_faces, fp)
  • pickle.load(fp)

But the file is not human readable. Is there an easy way to do it?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Mario Stefanutti
  • 232
  • 4
  • 22
  • 2
    *"the file is not human readable"* - so what? It's not supposed to be. – jonrsharpe Oct 16 '16 at 20:11
  • you could use `json` which uses the same interface or `eval` if you're brave. You'll have to compromise on the format a bit if you're using `json`. – Reut Sharabani Oct 16 '16 at 20:11
  • Possibly a duplicate of [Python human readable object serialization](http://stackoverflow.com/questions/408866/python-human-readable-object-serialization?rq=1) – Tammo Heeren Oct 16 '16 at 20:36

1 Answers1

1

Try the json module.

import json

g_faces = [[(3,2), (3,5)],[(2,4), (1,3), (1,3)],[(1,2), (3,4), (6,7)]]

json.dump(g_faces, open('test.json', 'w'))

g_faces = json.load(open('test.json'))

# cast back to tuples
g_faces = [[tuple(l) for l in L] for L in g_faces]
Tammo Heeren
  • 1,966
  • 3
  • 15
  • 20